Laravel Mail Template with Array - php

I created a simple mail sender. The problem is [1]
[1]: http://i.stack.imgur.com/uJHmB.png here. ı can't add the contacts names at the mail. Plase help me.
My mail send controller.
public function sendMail($id) {
$compaign = Compaign::findOrFail($id);
$group = Group::findOrFail($compaign->group);
$contacts = Contact::all()->where('group', $group->id);
if($contacts->count() <= 0) {
Session::flash('error', 'No recipients found!');
return redirect()->route('compaign.index');
}
foreach ($contacts as $contact) {
$data = [
'compaign' => $compaign,
'group' => $group,
'contact' => $contact,
];
Mail::send('mail', $data, function ($message) use ($data) {
$message->from($data['compaign']->femail, $data['compaign']->fname);
$message->to($data['contact']->email, $data['contact']->name)->subject($data['compaign']->subject);
});
}
Session::flash('success', 'Successfully sent the campaign');
return redirect()->route('compaign.index');
}
my mail.blade.php
{!!$compaign->content!!}

In your controller:
Mail::send('mail',array('compaign' => $data), ($message) use ($data) {
$message->from($data['compaign']->femail, $data['compaign']->fname);
$message->to($data['contact']->email, $data['contact']->name)->subject($data['compaign']->subject);
});

This should work:
public function sendMail($id)
{
$compaign = Compaign::findOrFail($id);
$group = Group::findOrFail($compaign->group);
$contacts = Contact::where('group', $group->id)->get();
if( ! $contacts->count()) {
Session::flash('error', 'No recipients found!');
return redirect()->route('compaign.index');
}
$data = [
'compaign' => $compaign,
'group' => $group,
'contacts' => $contacts
];
foreach ($contacts as $contact) {
Mail::send('mail', $data, function ($message) use ($compaign, $contact) {
$message->from($compaign->femail, $compaign->fname);
$message->to($contact->email, $contact->name);
$message->subject($compaign->subject);
});
}
Session::flash('success', 'Successfully sent the campaign');
return redirect()->route('compaign.index');
}
in blade
#foreach($contacts as $contact)
{!! $contact->email !!}
{!! $compaign-fname !!}
#endforeach
If not please dump the $compaign and $contacts variables.

Related

email function not passing variable to view

i want to pass a variable $data to my email views but i get undefined variable.
this is the controller method
public function broadcastemail(Request $request)
{
$this->validate($request,
[
'subject' => 'required',
'emailMessage' => 'required'
]);
$emailMessage = $request->emailMessage;
$data['emailMessage'] = $emailMessage;
Mail::send('backend.user.emailMessage', $data, function($message)
{
$subject = request()->subject;
$user = User::find('31');
$email = $user->email;
$name = $user->first_name;
$message->to($email, $name)->subject($subject)->with('data',$data);
});
//Mail::to($to)->send($data);
//send_email($to, $name, $subject, $message);
return back()->withSuccess('Mail Sent Successfuly');
}
and this is my view
<p>{{$data['emailMessage']}}</p>
try to use {{ $emailMessage }} instead of {{$data['emailMessage']}} in your view and use keyword for using inside the closure function of MAIL

Laravel, can only flash error messages within controller?

I'm using this to flash error messages within my UserController (using Toastr);
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:200',
'email' => 'required|email|unique:users,email,'. Auth::id(),
'phone' => 'alpha_num|nullable|min:8',
]);
if ($validator->fails()) {
Toastr::error('Changes not saved', 'Error');
return back();
}
$user = Auth::user();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phone = $request->input('phone');
$user->save();
Toastr::success('Changes saved', 'OK');
return back();
}
I would like to use Form Request for my validation, but keep running into problems when trying to flash (toastr) error messages.
Do one of you have an example of toastr used with Form Request? I have read the documentation like 10 times, but can't find a solution :(
https://laravel.com/docs/5.7/validation
This used to work about a year ago, but not anymore:
# Error messages
protected function formatErrors(Validator $validator)
{
$messages = $validator->messages();
foreach ($messages->all() as $message)
{
Toastr::error($message, 'Fejl');
}
return $validator->errors()->all();
}
Use withValidator() in your form request
but I am using toaster package from yoeunes/toastr
public function withValidator($validator)
{
$messages = $validator->messages();
foreach ($messages->all() as $message)
{
toastr()->error ( $message, 'Error');
}
return $validator->errors()->all();
}
It works for me in Laravel 7.x
Try that, thanks!

Send notification for an email only if its an email of an user registered in the conference

I have a page where a user can send notifications for users that are registered in a conference. In this page the user can select that wants to send a notification for all participants registered in a conference. But the user can also select that he wants to send an email for a specific user registred in a conference. I have the code below to achieve this.
The notification for all participants registered in a specific conference is working fine.
The issue is in sending a notification for a specific email that the user introduce in the "participant_email" form field. The issue is that the email is sent to any email but the notification should only be sent to a user that has a registration in the conference, otherwise should appear an error.
Do you know how to achieve that? In the code below is working for the all participants case, that is, if the user send a notification for all participatns and there are no participants registered, the notification is not sent and it appears "There are no participants registered in the conference.". But how to achieve also that if the user is sending a notification for a specific email that is not an email of a user registered in the conference?
public function send(Request $request, $id){
$conference = Conference::find($id);
$message = $request->message;
$subject = $request->subject;
// if the user selected that wants to send email for a specific participant of the conference
if($request->send_to == "participant"){
$this->validate(request(), [
'participant_email' => 'required|email|exists:users,email',
]);
Mail::to($request->participant_email)->send(new Notification($conference, $message, $subject));
Session::flash('success', 'Notification sent.');
return redirect()->back();
}
// if the user selected that wants to send an email for all participants of the conference
if($request->send_to == "all"){
$sendTo = User::whereHas('registrations', function ($query) use($id) {
$query->where('conference_id', '=', $id);
})->get();
}else{
$sendTo = User::whereHas('registrations.participants.registration_type', function ($query) use ($id, $request) {
$query->where('id', '=', $request->send_to)
->where('conference_id', '=', $id);
})->whereHas('registrations', function ($query) use ($id) {
$query->where('conference_id', '=', $id);
})->get();
}
foreach($sendTo as $user){
$usersEmail[] = $user->email;
}
if(isset($usersEmail)) {
foreach ($usersEmail as $userEmail) {
Mail::to($userEmail)->send(new Notification($conference, $message, $subject));
}
Session::flash('success', 'Notification sent with success.');
return redirect()->back();
}
else{
Session::flash('no_participants', 'There are no participants registered in the conference.');
return redirect()->back();
}
}
Updated code:
class NotificationController extends Controller
{
public function index($id){
$conference = Conference::find($id);
$registrationType = RegistrationType::where('conference_id', $id)->get();
return view('notifications.index')->with('conference', $conference)->with('registrationType', $registrationType);
}
public function send(Request $request, $id){
$conference = Conference::find($id);
$this->validate(request(), [
'send_to' => 'required',
'subject' => 'required',
'message' => 'required' // The message field is required.
]);
$message = $request->message;
$subject = $request->subject;
if($request->send_to == "participant"){
$this->validate(request(), $this->participantRules($id));
$emails[] = $request->participant_email;
}
else if($request->send_to == "all"){
$emails = User::whereHas('registrations', function ($query) use($id) {
$query->where('conference_id', '=', $id);
})->pluck('email');
}
else{
$emails = User::whereHas('registrations.participants.registration_type', function ($query) use ($id, $request) {
$query->where('id', '=', $request->send_to)
->where('conference_id', '=', $id);
})->whereHas('registrations', function ($query) use ($id) {
$query->where('conference_id', '=', $id);
})->get(); // use pluck('email') instead of get to select only email
}
if(count($emails) > 0) {
$this->sendNotification($emails, $conference, $request);
Session::flash('success', 'Notificação enviada com sucesso.');
return redirect()->back();
}else{
Session::flash('no_participants', 'There are no participants registered in the conference.');
return redirect()->back();
}
}
protected function participantRules($conferenceID){
return [
'email' => [
'required',
'email',
Rule::exists('users')->where(function ($query) use ($conferenceID) {
$query->whereHas('registrations', function ($query) use($conferenceID) {
$query->where('conference_id', '=', $conferenceID);
});
}),
],
];
}
protected function sendNotification(array $emails, $conference, $request){
foreach ($emails as $userEmail) {
Mail::to($userEmail)->send(new Notification($conference, $request->message, $request->subject));
}
Session::flash('success', 'Notificaiton sent with success.');
return redirect()->back();
}
}
You can add extra filter to exists validation like this
public function send(Request $request, $id){
$conference = Conference::find($id);
$message = $request->message;
$subject = $request->subject;
$emails = [];
if($request->send_to == "participant"){
$this->validate(request(), $this->participantRules($id));
$emails = User::whereHas('registrations', function ($query) use($id) {
$query->where('conference_id', '=', $id);
})->where('email', $request->participant_email)->pluck('email');
}else if($request->send_to == "all"){
$emails = User::whereHas('registrations', function ($query) use($id) {
$query->where('conference_id', '=', $id);
})->pluck('email');
}else{
$emails = User::whereHas('registrations.participants.registration_type', function ($query) use ($id, $request) {
$query->where('id', '=', $request->send_to)
->where('conference_id', '=', $id);
})->whereHas('registrations', function ($query) use ($id) {
$query->where('conference_id', '=', $id);
})->pluck('email');
}
if(count($emails) > 0) {
$this->sendNotification($emails, $conference, $request);
Session::flash('success', 'Notification sent with success.');
return redirect()->back();
}else{
Session::flash('no_participants', 'There are no participants registered in the conference.');
return redirect()->back();
}
}
Validation Rules
protected function participantRules($conferenceId){
return [
'participant_email' => 'required|email'
];
}
Send notification
protected function sendNotification($emails, $conference, $request){
foreach ($emails as $userEmail) {
Mail::to($userEmail)->send(new Notification($conference, $request->message, $request->subject));
}
}

Show the subject and message sending email with Mail::to

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);
});

Getting "Undefined variable: emails" in Laravel 5.4

Why am I getting "Undefined variable: emails" in Laravel 5.4, but the same code is working fine in Laravel 5.2? Below is a code snipped. Don't think this matters but I'm using PHP 7.1.3.
public function send(Request $request) {
$emails = "";
try {
$emails = [$request->input('to'), "john.doe#gmail.com"];
Mail::send('email.contact', ['request' => $request], function($message) use ($request) {
$message->from($request->input('email'), $request->input('email'));
$message->to($emails[0], $emails[0])
->cc($emails[1], $emails[1])
->subject("Contact Us");
});
$response = array (
'success' => true,
'message' => 'Message sent.',
$request
);
}
catch(Exception $e) {
$response = array (
'success' => false,
'message' => $e->getMessage(),
$request
);
}
// return Response::json( $response );
return $response;
}
The issue is here:
use ($request) {
to use $emails inside the anonymous function you have to pass it here like:
use ($request, $emails) {
Now you can use it.
Anonymous function reference
Just simply use the $emails variable in the anonymous function along with $request variable.
Full code to give this it a try.
public function send(Request $request) {
$emails = "";
try {
$emails = [$request->input('to'), "john.doe#gmail.com"];
Mail::send('email.contact', ['request' => $request], function($message) use ($request, $emails) {
# Here add $emails variable in use list.
$message->from($request->input('email'), $request->input('email'));
$message->to($emails[0], $emails[0])
->cc($emails[1], $emails[1])
->subject("Contact Us");
});
$response = array (
'success' => true,
'message' => 'Message sent.',
$request
);
}
catch(Exception $e) {
$response = array (
'success' => false,
'message' => $e->getMessage(),
$request
);
}
// return Response::json( $response );
return $response;
}
Hope this helps.

Categories