Laravel/Lumen email trimming for api - php

I am developing an api using Laravel/Lumen. I have seen very few users are complaining that even though their emails are completely fine, my api response says The email must be a valid email address.
What I have seen is that they are giving a space by mistake after their email like 'noob#user.com '. As a result the email is not accepted by the system. What I'm using in my code so far is:
try {
$this->validate($request, [
'first_name' => 'required|min:3|max:40',
'last_name' => 'required|min:3|max:40',
'email' => 'required|email|unique:clients,email',
'profile_photo' => ''
]);
} catch (ValidationException $e) {
return response()->json($this->clientTransformer->validationFailed($e), 200);
}
I have tried adding the following lines inside the first line of try block but failed to change the $request object property.
try{
$request->email = trim($request->email, ' '); //<= or
$request->email = str_replace(' ', '', $request->email); // <= this line
$this->validate($request, [
'first_name' => 'required|min:3|max:40',
'last_name' => 'required|min:3|max:40',
'email' => 'required|email|unique:clients,email',
'profile_photo' => ''
]);
}
but these arent working. this is passing the exact same email to the validate method. Is there any quick way to do it?

You can use:
$request->replace(array('email' => trim($request->email)));
or
$request->merge(array('email' => trim($request->email)));
Source:
https://laracasts.com/discuss/channels/general-discussion/laravel-5-modify-input-before-validation

Related

How to save emails in an email list on SendGrid using Laravel?

I'm working on a functionality where once a user signs up for an account, he will start getting a series of email throughout a time period (email drips).
I'm using Laravel. I need to grab the email on sign up and save it on an email list on SendGrid. But I don't find this on the sendgrid/sendgrid-php package's docs.
So, would you please tell me how I may implement this?
It can be done with the sendgrid-php package:
use SendGrid;
$api = new SendGrid(YOUR_API_KEY);
$contacts = [
[
'email' => "email#something",
'address_line_1' => '',
'city' => '',
'country' => '',
'first_name' => '',
'last_name' => '',
etc....
]
]
$request_body = [
'contacts' => $contacts
];
$response = $api->client->marketing()->contacts()->put($request_body);
if($response->statusCode() !== 202) {
// error has occured
}

URL has problems in laravel app wihile using S3 on local machine

Imagine you've uploaded a file on a S3 bucket or any type of external storage, right? the address might be :
storage.mystie.com/file
and the browser sees this like:
https://storage.mysite.com/file
but the app I'm working on, sends it like this:
//https://storage.mysite.com
and it results in this error:
Error executing "ListObjects" on "//https://IP"; AWS HTTP error: cURL error 6: Could not resolve host:
What's my problem? is it related to my .env file?!
I've implemented "AWS S3" in one of my Laravel's project when I'm going to save user data and upload his profile picture on s3 storage, while updating that image unlink the previous one and then upload the newest picture.
While storing User's Information code was like-this:
$user = User::create([
'first_name' => preg_replace('!\s+!', ' ', ucfirst($user['first_name'])),
'last_name' => preg_replace('!\s+!', ' ', ucfirst($user['last_name'])),
'email' => strtolower($user['email']),
'phone' => $user['phone'],
'address' => $user['address'],
'avatar' => $this->avatar?env('s3').Storage::disk('s3')->put('/profile',$this->avatar,'public'):'',
'type' => 'business',
'password' => bcrypt('business123456789'),
'meta' => $user['meta']
]);
While updating User's Data:
$filne_name = $this->old_avatar;
if($_FILES['avatar']['size'] > 0 && env('image-upload') == 'true')
{
if(!empty($this->old_avatar))
{
$image = pathinfo($this->old_avatar);
$response = Storage::disk('s3')->exists('/profile/'.$image['basename']);
if($response)
{
Storage::disk('s3')->delete('/profile/'.$image['basename']);
}
}
$filne_name = env('s3').Storage::disk('s3')->put('/profile',$this->avatar,'public');
}
return User::where('id',$this->segment(3))->update([
'first_name' => preg_replace('!\s+!', ' ', ucfirst($user['first_name'])),
'last_name' => preg_replace('!\s+!', ' ', ucfirst($user['last_name'])),
'email' => $user['email'],
'phone' => $user['phone'],
'address' => $user['address'],
'avatar' => $filne_name,
'meta' => json_encode($user['meta'])
]);
And in my .env
s3='https://bucket_link.com/' (That was s3 bucket link)

If stament in a class call

I am trying to put an if statement when calling a class, but the operator -> produces a problem I cant figure out. So calling the class like:
$email = WP_Mail::init()
->to('myemail#hotmail.com')
->subject('This is an automated message pleas do not reply')
->template(plugin_dir_path( __DIR__ ) .'email-templates/email.php', [
'name' => 'Anthony Budd',
'email' => 'test#test.com',
'skills' => [
'PHP',
'AWS',
]
]);
if (site_url() === 'mysite'){
->send();
}else {
->render();
echo $email;
}
normally it would look like:
$email = WP_Mail::init()
->to('john.doe#gmail.com')
->template(get_template_directory() .'/emails/demo.php', [
'name' => 'Anthony Budd',
'location' => 'London',
'skills' => [
'PHP',
'AWS',
]
])
->send();
this above produces an error due to the operator, how can I return "->render()" or "->send()". I want to display the data if on my dev computer but when I push the code to me server it needs to send the email.
You're missing the object $email before calling the methods. Take a look at this:
if (site_url() === 'mysite'){
$email->send();
}else {
$email->render();
echo $email;
}

php foreach function performance problems

php foreach function should send 1 SMS but it sends 2-3 for each contact.
The code should send invitations through email and SMS. But the contacts are receiving sometimes 2 or three invitation at the same time which gets the SMS to be blocked.
public function handle(QRCodeEmail $mail) {
try {
foreach ($this->event->contacts as $eventContact) {
if($eventContact->pivot->sent_date) {
continue;
}
if($eventContact->email) {
$mail->subject = $this->event->name;
$mail->setEmail($eventContact->email);
$mail->setName($eventContact->first_name . ' ' . $eventContact->last_name);
$mail->send([
'name' => $this->event->name ?? '',
'hostName' => $this->event->host_name ?? '',
'suffix' => $eventContact->suffix,
'firstName' => $eventContact->first_name,
'lastName' => $eventContact->last_name,
'data' => $eventContact->pivot->hash,
]);
}
\Curl::to(env('SMS_GATEWAY_URL'))
->withData([
'username' => env('SMS_GATEWAY_USERNAME'),
'password' => env('SMS_GATEWAY_PASSWORD'),
'message' => $this->generateBodyForSms($eventContact, env('INVITATION_LINK') . $eventContact->pivot->hash),
'numbers' => $eventContact->phone,
'sender' => env('SMS_GATEWAY_SENDER'),
])
->post();
(EventsContacts::find($eventContact->pivot->id))->update([
'sent_date' => Carbon::create()->format('Y-m-d H:i:s')
]);
}
$this->job->delete();
} catch (\Exception $e) {
$this->job->delete();
throw new \Exception($e);
}
}
Some possibilities
Maybe you should try array_unique ( http://php.net/manual/en/function.array-unique.php ) (Check the unique_multidim_array function posted in the comments of array_unique.)
Is it possible that you have mulitple records (with distinct "primary key" with the same number ? Then store phone numbers that have already received the SMS and check against that list before sending a new one.
Maybe your exit condition if($eventContact->pivot->sent_date) doesn't work as inteted.

SparkPost PHP reply_to not working

I am using SparkPost PHP API for sending emails and it seems like reply_to feature is not working. I tried to both ways with headers and with reply_to field. Any ideas what could be wrong? Domain name of reply_to emails is different as senders one. I didn't found any restrictions regarding this in their documentation. Any ideas?
Here is my code:
$emailData = array(
'from'=> $data["from_name"].' <'.$data["from_email"].'>',
'html'=> $data["html"],
'inline_css' => true,
'transactional' => true,
'subject'=> $data["subject"],
'recipients'=> $rec["r"]
);
if(isset($data["headers"]["Reply-To"]))
$emailData['reply_to'] = $data["headers"]["Reply-To"];
try {
// Build your email and send it!
$this->mandrill->transmission->send($emailData);
} catch (\Exception $err) {
echo "<pre>";
print_r($err);
echo "</pre>";
}
Regarding: SparkPost PHP ReplyTo, reply_to, Reply
For anyone else wondering the same thing. Here's my implementation using SparkPost client library for PHP v2.1. I hope it helps.
I used the transmissions endpoint as seen in the docs.
https://github.com/sparkpost/php-sparkpost
$promise = $sparky->transmissions->post([
'content' => [
'from' => [
'name' => 'Company Name',
'email' => 'noreply#company.com',
],
'reply_to' => $email,
'subject' => 'Some Subject',
'html' => $html_message,
'text' => $text_message,
],
'substitution_data' => $subData,
'recipients' => [
[
'address' => [
'name' => 'My Recipient',
'email' => 'me#company.com',
]
],
],
]);
Thank god for slack :)
Solution is that SparkPost has different name for parameters in API documentation. Correct parameter for PHP API is not reply_to (as it's written in doc) but replyTo.

Categories