I am trying to send two emails at the same time when the user submits contact form. One email to the website owner and other to the user as autoresponse. I have been trying to do this for about last 4 hours and tried different solutions on internet but I am totally lost. Here is my code to send an email
public function contactForm(Request $request)
{
$parameters = Input::get();
$email = Input::get('email');
$inquiryType = Input::get('type_inquiry');
foreach ([
'contactmessage' => 'Message',
'email' => 'Email',
'phone' => 'Phone',
'first_name' => 'Contact Name',
'g-recaptcha-response' => 'Captcha',
] as $key => $label) {
if (!isset($parameters[$key]) || empty($parameters[$key])) {
return response()->json(
[
'success' => false,
'error' => "{$label} cannot be empty",
]
);
}
}
$recipients = 'abc#gmail.com';
// if page set, try to get recipients from the page settings
if (Input::get('page_id')) {
$page = Page::find(Input::get('page_id'));
if ($page && !empty($page->recipients)) {
$recipients = explode(',', $page->recipients);
}
}
try {
$res = Mail::send(
'emails.contact',
$parameters,
function (Message $message) use ($recipients) {
$message->subject('Contact message');
if (is_array($recipients)) {
// email to first address
$message->to(array_shift($recipients));
// cc others
$message->cc($recipients);
} else {
$message->to($recipients);
}
}
);
} catch (\Exception $e) {
return response()->json(
[
'success' => false,
'error' => $e->getMessage(),
]
);
}
if($inquiryType == 'Rental Inquiry'){
Mail::send(
'emails.autoresponse',
'',
function (Message $message) use ($email) {
$message->subject('Thank you for inquiring');
if (is_array($email) {
// email to first address
$message->to(array_shift($email);
// cc others
$message->cc($email);
} else {
$message->to($email);
}
}
);
}
return response()->json(
[
'success' => $res,
]
);
}
I have tried to do the same thing by different methods but none of them are working. Please help me. This is the first time I am sending multiple emails using laravel. I think I am doing a big and silly mistake somewhere.
Thank you.
You have a missing closing parenthesis near is_array($email)
$message->subject('Thank you for inquiring');
if (is_array($email)) {
Also i would you use laravel's validator to check for required input. Another suggestion would be to use queues for mails. Sending two mails in a single request might cause your page load time to increase significantly.
The best way is create one Laravel Jobs
php artisan queue:table
php artisan migrate
php artisan make:job SendEmail
Edit your .env
QUEUE_DRIVER=database
Edit your app /Jobs/SendEmail.php
namespace App\Jobs;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Mail\Mailer;
class SendEmail extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $subject;
protected $view;
protected $data;
protected $email;
/**
* SendEmail constructor.
* #param $subject
* #param $data
* #param $view
* #param $email
*/
public function __construct($subject, $data, $view, $email)
{
$this->subject = $subject;
$this->data = $data;
$this->email = $email;
$this->view = $view;
}
/**
* Execute the job.
* #param $mailer
* #return void
*/
public function handle(Mailer $mailer)
{
$email = $this->email;
$subject = $this->subject;
$view = $this->view;
$mailer->send($view, $this->data,
function ($message) use ($email, $subject) {
$message->to($email)
->subject($subject);
}
);
}
}
And handle in your controller
use App\Jobs\SendEmail;
public function contactForm(Request $request) {
//TODO Configure Subject
$subjectOwner = 'Your Email Subject For Owner';
$subjectUser = 'Your Email Subject For User';
//TODO Configure Email
$ownerEmail = 'ownerEmail#gmail.com';
$userEmail = 'userEmail#gmail.com';
//TODO Configure Data Email send to email blade viewer
$dataEmail = [
'lang' => 'en',
'user_name' => 'User Name'
];
//emails.owner mean emails/owner.blade.php
//emails.admin mean emails/admin.blade.php
$jobOwner = (new SendEmail($subjectOwner, $dataEmail, "emails.owner" , $ownerEmail))->onQueue('emails');
dispatch($jobOwner);
$jobUser = (new SendEmail($subjectUser, $dataEmail, "emails.admin" , $userEmail))->onQueue('emails');
dispatch($jobUser);
}
And try command
//IF You using Laravel 5.2
php artisan queue:listen --queue=emails
//IF You using Laravel >5.3
php artisan queue:work
Related
I have a small Symfony project I want to document with doxygen. There are two .php files that should be included. One is documented, the other is not, and I cannot figure out why that may be.
Folder structure is:
project
└--src
|--Controller
| └--FormController.php
└--Model
└--Inquiry.php
Doxygen is reading and parsing both files...
Reading /form-handler/src/Controller/FormController.php...
Parsing file /form-handler/src/Controller/FormController.php...
Reading /form-handler/src/Model/Inquiry.php...
Parsing file /form-handler/src/Model/Inquiry.php...
...but only documents FormController.php, not Inquiry.php:
Generating docs for compound App::Controller::FormController...
For some reason doxygen does not seem to recognizeInquiry.php as a class.
What I have tried:
Removed decorators from docstrings that might offend doxygen.
Checked format of docstrings
Enabled/disabled various Doxyfile options
FormController.php:
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Model\Inquiry;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* Handles incoming requests.
*/
class FormController extends AbstractController
{
/**
* Handles POST requests.
*
* #return Response contains JSON object with 'message' value
*/
#[Route('/', methods: ['POST'])]
public function handleRequest(
HttpClientInterface $client,
Inquiry $inquiry,
LoggerInterface $logger,
RateLimiterFactory $formApiLimiter,
Request $request,
): Response {
$logger->debug('Received a POST request');
// set up a rate limiter by IP
// rules are defined in /config/packages/rate-limiter.yaml
$limiter = $formApiLimiter->create($request->getClientIp());
$limit = $limiter->consume();
// configure headers exposing rate limit info
$headers = [
'Content-Type' => 'application/json',
'X-RateLimit-Remaining' => $limit->getRemainingTokens(),
'X-RateLimit-Retry-After' => $limit->getRetryAfter()->getTimestamp(),
'X-RateLimit-Limit' => $limit->getLimit(),
];
if (false === $limit->isAccepted()) {
return new Response(
content: json_encode(['message' => null]),
status: Response::HTTP_TOO_MANY_REQUESTS,
headers: $headers
);
}
// make sure all required fields are included in request and not empty
$requiredFields = ['subject', 'message', 'consent', 'h-captcha-response'];
$providedFields = $request->request->keys();
foreach ($requiredFields as $field) {
if (!in_array($field, $providedFields)) {
return new Response(
content: json_encode(['message' => "Pflichtfeld '".$field."' fehlt."]),
status: Response::HTTP_BAD_REQUEST,
headers: $headers
);
} elseif ('' == filter_var($request->request->get($field), FILTER_SANITIZE_SPECIAL_CHARS)) {
return new Response(
content: json_encode(['message' => "Pflichtfeld '".$field."' darf nicht leer sein."]),
status: Response::HTTP_BAD_REQUEST,
headers: $headers
);
}
}
// verify captcha success
$captcha = filter_var($request->request->get('h-captcha-response'), FILTER_SANITIZE_SPECIAL_CHARS);
$data = [
'secret' => $this->getParameter('app.captcha.secret'),
'response' => $captcha,
];
try {
$hCaptchaResponse = $client->request(
method: 'POST',
url: 'https://hcaptcha.com/siteverify',
options: [
'body' => $data,
],
);
$hCaptchaResponseJson = json_decode($hCaptchaResponse->getContent(), true);
if (!$hCaptchaResponseJson['success']) {
return new Response(
content: json_encode(['message' => 'Captcha fehlgeschlagen']),
status: Response::HTTP_BAD_REQUEST,
headers: $headers
);
}
// exceptions on the side of hCaptcha are logged, but the request is processed anyway
} catch (TransportExceptionInterface $e) {
$logger->debug('Could not reach hCaptcha verification server: '.$e);
} catch (ClientExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface $e) {
$logger->debug('Error when verifying hCaptcha response: '.$e);
}
// get values from request data
$name = filter_var($request->request->get('name'), FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_var($request->request->get('email'), FILTER_SANITIZE_EMAIL);
$phone = filter_var($request->request->get('phone'), FILTER_SANITIZE_SPECIAL_CHARS);
$subject = filter_var($request->request->get('subject'), FILTER_SANITIZE_SPECIAL_CHARS);
$message = filter_var($request->request->get('message'), FILTER_SANITIZE_SPECIAL_CHARS);
$consent = filter_var($request->request->get('consent'), FILTER_SANITIZE_SPECIAL_CHARS);
// translate into a boolean (else the string 'false' will be evaluated as true)
$consent = filter_var($consent, FILTER_VALIDATE_BOOLEAN);
// populate Inquiry with request data
$inquiry->createInquiry(
subject: $subject,
message: $message,
consent: $consent,
name: $name,
email: $email,
phone: $phone,
);
// validate Inquiry
$validationResult = $inquiry->validateInquiry();
// if Inquiry is invalid, return validation violation message(s)
if (count($validationResult) > 0) {
$logger->debug($validationResult);
// assemble list of error messages
$validationMessages = [];
foreach ($validationResult as $result) {
$validationMessages += [$result->getPropertyPath() => $result->getMessage()];
}
return new Response(
content: json_encode([
'message' => 'Anfrage enthält ungültige Werte',
'errors' => $validationMessages,
]),
status: Response::HTTP_BAD_REQUEST,
headers: $headers
);
}
// send mail to office
$emailResult = $inquiry->sendOfficeEmail();
$logger->debug(implode(' ,', $emailResult));
$message = 'Die Anfrage war erfolgreich';
if (!$emailResult['success']) {
$message = 'Die Anfrage war nicht erfolgreich.';
}
// TODO compile email to user
$data = [
'message' => $message,
'officeEmail' => $emailResult,
'confirmationEmail' => true,
];
return new Response(
content: json_encode($data),
status: Response::HTTP_OK,
headers: $headers
);
}
/**
* Handles disallowed request methods.
*
* #return Response contains JSON object with 'message' value
*/
#[Route('/', condition: "context.getMethod() not in ['POST']")]
public function handleDisallowedMethods(LoggerInterface $logger): Response
{
$logger->debug('Received a request with a disallowed method.');
return new Response(
content: json_encode(['message' => 'Only POST requests allowed']),
status: Response::HTTP_METHOD_NOT_ALLOWED
);
}
}
Inquiry.php:
<?php
declare(strict_types=1);
namespace App\Model;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Represents an inquiry received from the front end.
*
* The required fields 'subject', 'message', and
* 'consent' must be provided to the constructor.
*/
class Inquiry
{
private string $name;
private string $email;
private string $phone;
private string $subject;
private string $message;
private bool $consent;
private bool $validated = false;
/**
* #param LoggerInterface $logger
* #param MailerInterface $mailer
* #param array $officeRecipients configured in services.yaml
* #param ValidatorInterface $validator
*/
public function __construct(
private readonly LoggerInterface $logger,
private readonly MailerInterface $mailer,
private readonly array $officeRecipients,
private readonly ValidatorInterface $validator,
) {
}
/**
* Populates an inquiry with data.
*
* 'subject', 'message', and 'consent are required,
* all other values are optional.
*
* Sets 'validated' to false, in case createInquiry()
* is called multiple times.
*/
public function createInquiry(
string $subject,
string $message,
bool $consent,
string $name = '',
string $email = '',
string $phone = '',
): void {
$this->subject = $subject;
$this->message = $message;
$this->consent = $consent;
$this->name = $name;
$this->email = $email;
$this->phone = $phone;
$this->validated = false;
}
/**
* Validates the inquiry.
*
* If successful, sets 'validated' to true
*
* #return ConstraintViolationListInterface if valid: empty
* if not valid: list of validation violation messages
*/
public function validateInquiry(): ConstraintViolationListInterface
{
$validationResult = $this->validator->validate($this);
if (0 == count($validationResult)) {
$this->validated = true;
}
return $validationResult;
}
/**
* Sends an email with the customer inquiry data to the office.
*
* #return array containing 'success' boolean and 'message' string
*/
public function sendOfficeEmail(): array
{
if (!$this->validated) {
return [
'success' => false,
'message' => 'Inquiry has not been validated. Use Inquiry->validate() first',
];
}
// convert 'consent' and empty values in to human-readable format
$plainTextConsent = $this->consent ? 'Ja' : 'Nein';
$plainTextName = $this->name ?: 'Keine Angabe';
$plainTextEmail = $this->email ?: 'Keine Angabe';
$plainTextPhone = $this->phone ?: 'Keine Angabe';
$emailBody = <<<END
Das Kontaktformular hat eine Anfrage erhalten.
Betreff: $this->subject
Nachricht: $this->message
Einwilligung: $plainTextConsent
Name: $plainTextName
Email: $plainTextEmail
Telefon: $plainTextPhone
END;
$email = (new Email())
->to(...$this->officeRecipients)
->subject('Anfrage vom Kontaktformular')
->text($emailBody);
try {
$this->mailer->send($email);
$this->logger->debug('Email sent');
return [
'success' => true,
'message' => 'Email wurde gesendet',
];
} catch (TransportExceptionInterface $e) {
$this->logger->debug('Error sending email: '.$e);
return [
'success' => false,
'message' => 'Email konnte nicht gesendet werden: '.$e,
];
}
}
/**
* #codeCoverageIgnore
*/
public function sendConfirmationEmail(): string
{
return '';
}
/**
* Checks whether Inquiry has been validated.
*/
public function isValidated(): bool
{
return $this->validated;
}
}
Doxyfile (EDITED as per #albert's comment):
# Difference with default Doxyfile 1.9.3 (c0b9eafbfb53286ce31e75e2b6c976ee4d345473)
PROJECT_NAME = "Form handler"
PROJECT_BRIEF = "Stand-alone Symfony backend to handle contact forms."
OUTPUT_DIRECTORY = ./doc/
INPUT = ./src/ \
README.md
RECURSIVE = YES
EXCLUDE = ./src/Kernel.php
USE_MDFILE_AS_MAINPAGE = README.md
GENERATE_LATEX = NO
As of PHP version 7.3.0 the syntax of the here document changed slightly, see https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string. Prior to PHP 7.3.0, the closing identifier must begin in the first column of the line.
This has now been corrected in the proposed patch, pull request: https://github.com/doxygen/doxygen/pull/9398
Workarounds:
place the end identifier of the here document at the beginning of the line
place a doxygen conditional block /** \cond / / /* \endcond */ around the here document.
I find out that the Pdf I attached to my email does not show when delivered to my email in Mailtrap but it shows in the RAW data section.
My Controller Method to send an email:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'quantity' => 'required|numeric|digits:1',
]);
if ($request->quantity > 5) {
toastr()->error('Only 5 tickets per booking is allowed');
return redirect()->back();
}
$a = 0;
$file = array();
while ($a < $request->quantity) {
$ordercode = substr(md5(time() . mt_rand(1, 1000000)), 0, 22);
$qrcodepath = 'assets/payments/qrcodes/'.str_slug($request->name).time().'.png';
$qrcode = QrCode::format('png')->size(400)->generate($ordercode, $qrcodepath);
$data["name"] = $request->name;
$data["email"] = $request->email;
$data["qrcode"] = $qrcodepath;
$data["ordercode"] = $ordercode;
$pdf = PDF::loadView('pdf.payment', $data);
$pdfpath = 'assets/payments/pdf/'.str_slug($request->name).time().'.pdf';
$pdf->save($pdfpath);
$payment = Payment::create([
'fullname' => $request->name,
'qrcode' => $qrcodepath,
'ordercode' => $ordercode,
'email' => $request->email,
'quantity' => 1,
'pdfticket' => $pdfpath
]);
$file[] = $payment->pdfticket;
$a++;
sleep(1);
}
$data = array(
'name' => $payment->fullname,
'tickets' => $file,
);
Mail::to($payment->email)->send(new PurchaseComplete($data));
dd($payment->email);
toastr()->success('Payment created successfully');
return redirect()->back();
}
My Mailable:
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class PurchaseComplete extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$message = $this->subject('Ticket Purchase - CodeRed')->markdown('emails.purchase.complete')->with('data', $this->data);
$count = 0;
foreach ($this->data['tickets'] as $ticket) {
$count++;
$message->attach(asset($ticket), array(
'as' => 'ticket'.$count.'.pdf',
'mime' => 'application/pdf',
));
}
return $message;
}
}
My Email Markdown:
#component('mail::message')
# Hello {{ $data['name'] }}
Your Ticket Purchase: Please find attached files below.
Ensure you download the ticket and load it on your phone when you arrive!
You can also Login to your profile to download the Qrcode for a quick scan and copies of your tickets!
#component('mail::button', ['url' => route('login')])
Login
#endcomponent
If you have any further questions: contact us through the contact section on our website.
Thanks,<br>
{{ config('app.name') }}
#endcomponent
Mailtraps HTML output of the mail:
But in the RAW section: it shows that a pdf was attached:
I have searched the web and implemented practically every solution I found to try solving this problem but no success. I have tried using public_path(), storage_path(), attachData() and more! I just don't know how to proceed and make this work.
My bad for this: I didn't know Mailtrap displays attachments differently from other mail service providers...
I use the instructions https://laravel.com/docs/5.8/mail
to send an email later than expected, but I get an error when I try to send it:
ErrorException (E_ERROR)
Only mailables may be queued. (View: ....
Please for help.
My methods to send:
public static function sent_info_email_later ($data_f, $minuts) {
$data = json_decode($data_f);
$when = now()->addMinutes($minuts);
return Mail::later($when,'emails.message', ['title' => $data->subject, 'body' => $data->body], function ($message) use ($data, $when)
{
$message->from(env('MAIL_USERNAME'), 'NETPlatform24');
if(gettype($data->to) == 'array') {
$dest_to = $data->to;
} else {
$dest_to = explode(', ', $data->to)[0];
}
$message->to($dest_to);
$message->subject($data->subject);
return true;
});
}
and calling index.php
$data = json_encode(array('to' => 'my email', 'subject' => 'This email was send 1 min after run', 'body' => 'time now'.now().'<br> time send: '.now()->addMinutes(1)));
$send_mail = \App\Http\Controllers\Backend\Auth\Mail\MailController::sent_info_email_later($data, 1);
I wrote this code long time ago. I hope this will help to clarify. For each Cargo I send a email using queue.
<?php
public function mails_meeting($meeting, $group, $place, $date, $message, $user)
{
$subject = "meeting " . $group;
$cargos = Cargo::where('comision_id', '=', $meeting->comision_id)->where('active', '=', '1')->get();
foreach ($cargos as $cargo) {
$mail_reciever = $cargo->asambleista->user->email;
Mail::queue('correos.comision_mail', ['group' => $group, 'place' => $place,
'date' => $date, 'message' => $message, 'user' => $user],
function ($mail) use ($subject, $mail_reciever) {
$mail->from('siarcaf#gmail.com', 'Automatic mail system');
$mail->to($mail_reciever);
$mail->subject($subject);
});
}
return 0;
}
In your_app/config/mail.php .
'sendmail' => '/usr/sbin/sendmail -bs',
'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
],
.env file
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=your_conf
The error you're getting (and the docs) indicate that the second argument passed to the later method must be an instance of Illuminate\Mail\Mailable.
Where you currently have the string 'emails.message', you will need to replace this with an instance of Mailable that represents the email message that you're trying to send.
For example, create this file in /app/Mail (create the folder if it doesn't exist):
<?php
namespace App\Mail;
use Illuminate\Mail\Mailable;
use Illuminate\Contracts\Queue\ShouldQueue;
class InfoEmail extends Mailable implements ShouldQueue
{
public $subject;
public $body;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($subject, $body)
{
$this->subject = $subject;
$this->body = $body;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from(env('MAIL_USERNAME'), 'NETPlatform24')
->subject($this->subject)
->view('emails.message', ['title' => $this->subject, 'body' => $this->body]);
}
}
This assumes that 'emails.message' is the view file you intend to use for this email, located at /resources/views/emails/message.blade.php relative to your project's root. I'd actually recommend changing this to something a bit more descriptive.
You'll then need to change your sent_info_email_later method to something like this:
public static function sent_info_email_later ($data_f, $minuts) {
$data = json_decode($data_f);
$when = now()->addMinutes($minuts);
$recipients = is_array($data->to) ? $data->to : explode(', ', $data->to);
$recipients = array_filter(array_map('trim', $recipients));
$first_recipient = array_shift($recipients);
return Mail::to($first_recipient)
->cc($recipients)
->later($when, new InfoEmail($data->subject, $data->body));
}
I've taken the liberty of tidying up your recipients by extracting out the first recipient for the to and moving the rest to cc as this may play better with more email service providers.
Hope this helps!
I have the code below to send emails using the Mail::to function. But Im not understanding how to set the subject and body of the message with the Mail::to function. I have the code below that is working to send emails but without subject and the $message is also not appearing in the email.
Do you know how to properly achieve that? (Have subject and the $request->message in the email using Mail::to)
public function send(Request $request, $id){
$conference = Conference::find($id);
if($request->send_to == "participant"){
// if is to send only 1 email the Mail::to is called directly here
Mail::to($request->participant_email)->send(new Notification($conference));
return;
}
if($request->send_to == "all"){
// $sendTo = query to get a set of emails to send the email
}
else{
// $sendTo = query to get a another set of emails to send the email
}
foreach($sendTo as $user){
$usersEmail[] = $user->email;
}
$message = $request->message;
$subject = $request->subject;
foreach ($usersEmail as $userEmail){
Mail::to($userEmail)->send(new Notification($conference, $message));
}
}
In the class Notification I have:
class Notification extends Mailable
{
public $conference;
public function __construct(Conference $conference)
{
$this->conference = $conference;
}
public function build()
{
return $this->markdown('emails.notification');
}
}
In the view notifications.blade.php I have:
#component('mail::message')
# Notification relative to {{$conference->name}}
{{$message}}
Thanks,<br>
{{ config('app.name') }}
#endcomponent
Try something like this:
$emailData = array(
/* Email data */
'email' => 'user#email.com',
'name' => 'User name',
'subject' => 'Email subject',
);
Mail::send('emails.template_name', ['emailData' => $emailData], function ($m) use ($emailData) { // here it is a closure function, in which $emailData data is available in $m
$m->from('info#domain.com', 'Domain Name');
$m->to($emailData['email'], $emailData['name'])->subject($emailData['subject']);
});
try
{
Mail::send('emails.contact_form', ['data' => $data],
function($message) use ($data)
{
$message->from('emailasinenv#hosting.com', 'ShortName');
$message->to( $data['adminEmail'] )->subject("Contact Form" );
});
return true;
}
catch (\Exception $ex) {
$ex->getMessage();
return false;
}
As you already have one template in your code use that template, Pass the message to template
$subject = 'Email Subject';
Mail::send('emails.notification', ['message' => $message], function ($mail) use ($userEmail, $subject) {
$mail->from('info#domain.com', 'Domain Name');
$mail->to($userEmail)->subject($subject);
});
I have a weird problem with my Laravel application, whereby this code gets called twice once the validation rules kick in. I have abstracted validation logic into a separate class, but no matter how I consume the API (tried using Postman, and with jQuery) it still appears to run twice with the output looking like this:
called{"email":["The email has already been taken."],"country":["The country must be a number."]}called{"email":["The email has already been taken."],"country":["The country must be a number."]}
I am only expecting one JSON response. I'm tearing my hair out, tried on two different connections and can't seem to work out why the custom request is called twice. This is a new Laravel app, so there isn't much code to conflict with it.
//Create User Request extends standard request. Handles Validation
public function __construct(CreateUserRequest $request){
$this->request = $request;
}
public function register()
{
try{
$array = DB::transaction(function(){
$email = $this->request->input('email');
$password = $this->request->input('password');
$companyName = $this->request->input('companyName');
$userName = $this->request->input('name');
$country = $this->request->input('country');
$company = Company::create([
'name' => $companyName,
'active'=>true,
'country_id'=>$country
]);
$user = User::create([
'company_id' => $company->id,
'name'=>'admin',
'email' => $email,
'password' => $password,
'active' =>true
]);
if( !$company || !$user )
{
throw new \Exception('User not created for account');
}
return compact('company', 'user');
});
$token = JWTAuth::fromUser($array['user']);
return Response::json(compact('token'));
}
catch( Exception $e )
{
return Response::json(['error' => $e->getMessage() ], HttpResponse::HTTP_CONFLICT );
}
}
Then the validation custom Request..
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Response;
class CreateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
public function response(array $errors)
{
// return Response::json(['errorg' => $errors ], 200 );
echo('called');
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'email' => 'required|unique:users',
'password' => 'required',
'companyName' => 'required',
'name' => 'required',
'country' => 'required|numeric'
];
}
}
Interesting.
Try to remove CreateUserRequest $request parameter from __construct() and add it to your register() method like this: register(CreateUserRequest $request). And use your request by calling $request instead of $this->request.