send custom emails to cutomers with laravel - php

I have customer data in my database with their emails. In my case, i want to get user email from customer table and send a custom email to customer. I'm new to laravel and this is the very first time i'm working with laravel notification. Help me to do this!
I have created this SendMailController:
public function sendNotifications(Request $request, $id)
{
$id = $request->id;
$customer_id = DB::table('jobs')->select('customers_id')->where('id', '=', $id)->get();
$customer_email = DB::table('customer')->select('email')->where('id', '=', $customer_id)->get();
$customer_firstname = DB::table('customer')->select('firstname')->where('id', '=', $customer_id)->get();
sendEmail($customer_firstname, $customer_email);
return view('admin.sendNotifications');
}
I have created a sendEmail Notification class:
class sendEmail extends Notification
{
use Queueable;
public function __construct($customer_firstname, $customer_email)
{
$this->customer_email = $customer_email;
$this->customer_firstname = $customer_firstname;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->error()
->subject('Thank you!')
->from('hashankannangara#gmail.com', 'Sender')
->to($this->customer_email)
->line($this->customer_firstname.''.'Thanks for got services from us!');
}
public function toArray($notifiable)
{
return [
//
];
}
}
How can i pass the customer email to to() function? I want to display customer first name in email with Thanking them. How can i use a custom template and add to this email? I appreciate if you can help me.

https://laravel.com/docs/6.x/notifications#mail-notifications
You can use something like this in toMail method:
return (new CustomMail($this->customer))->to($this->customer->email);
and when you call notify you must pass a customer

use Mail;
$data = 'set data variable pass in view'
$email= 'receiver' email'
Mail::send('here set your file for view (ex. email.access(blade))', $data, function ($message) use ($email) {
$message->from('sender mail','Title')->subject('Register');
$message->to($email);
});

Related

How to make a notification to the dynamic cell phone with Laravel?

I made my code where an administrator can send a message to a group, and soon all users within that group receive notification on the mobile app:
public function create(Request $request)
{
if(!($error = $this->isNotValidate($request))){
//Log::error(print_r("validado", true));
$message = Message::create($request->toArray());
$message->recives()->attach($request->recive_ids);
foreach($message->recives as $group){
foreach($group->users as $user){
$user->notify(new NotificationMessage($message));
}
}
$response = ['message' => $message];
return response($response, 200);
}
return response($error, 422);
}
I used the library: https://github.com/laravel-notification-channels/fcm it is working he send the notification to the mobile through the firebase.
my difficulty is that in the toFcm function I want to retrieve the message to build the notification I'm sending:
public function toFcm($notifiable)
{
return FcmMessage::create()
->setData(['message_id' => $this->invoice->id, 'message_created' => $this->invoice->created_at])
->setNotification(\NotificationChannels\Fcm\Resources\Notification::create()
->setTitle($this->invoice->title)
->setBody($this->invoice->content)
//->setImage('http://example.com/url-to-image-here.png')
)->setAndroid(
AndroidConfig::create()
->setFcmOptions(AndroidFcmOptions::create()->setAnalyticsLabel('analytics'))
->setNotification(AndroidNotification::create()->setColor('#0A0A0A'))
)->setApns(
ApnsConfig::create()
->setFcmOptions(ApnsFcmOptions::create()->setAnalyticsLabel('analytics_ios')));
}
I thought that in the variable $this->invoice or in the $notifiable would come the $message that I am passing as a parameter in the creation, but it does not pass, both are returning the user.
does anyone know how i can make this dynamic notification with my message data?
UPDATE
class NotificationMessage extends Notification
{
/**
* Specifies the user's FCM token
*
* #return string|array
*/
public function routeNotificationForFcm()
{
return $this->fcm_token;
}
public function via($notifiable)
{
return [FcmChannel::class];
}
public function toFcm($notifiable)
{
return FcmMessage::create()
->setData(['message_id' => $notifiable->id, 'message_created' => $notifiable->created_at])
->setNotification(\NotificationChannels\Fcm\Resources\Notification::create()
->setTitle($notifiable->title)
->setBody($notifiable->content)
//->setImage('http://example.com/url-to-image-here.png')
)->setAndroid(
AndroidConfig::create()
->setFcmOptions(AndroidFcmOptions::create()->setAnalyticsLabel('analytics'))
->setNotification(AndroidNotification::create()->setColor('#0A0A0A'))
)->setApns(
ApnsConfig::create()
->setFcmOptions(ApnsFcmOptions::create()->setAnalyticsLabel('analytics_ios')));
}
// optional method when using kreait/laravel-firebase:^3.0, this method can be omitted, defaults to the default project
public function fcmProject($notifiable, $message)
{
// $message is what is returned by `toFcm`
return 'app'; // name of the firebase project to use
}
}
I decided to invert the logic of who was my notify, now instead of the user being the notify, my message became
In my control I'm even simpler:
public function create(Request $request)
{
if(!($error = $this->isNotValidate($request))){
//Log::error(print_r("validado", true));
$message = Message::create($request->toArray());
$message->recives()->attach($request->recive_ids);
$message->notify(new NotificationMessage);
$response = ['message' => $message];
return response($response, 200);
}
return response($error, 422);
}
in my message template I made the following changes:
use Illuminate\Notifications\Notifiable;
...
class Message extends BaseModel
{
use Notifiable;
...
public function routeNotificationForFcm()
{
$tokens = [];
foreach($this->recives as $group){
foreach($group->users as $user){
$tokens = array_merge($tokens, $user->notifications()->pluck('token')->toArray());
}
}
return $tokens;
}
}
with that in my variable $notifiable started to receive the information of the message and then it was easy to pass them as parameter.

Larvel Notification Not working for custom email field

i want to send notification to my clinic owner, when a clinic is added by admin. The following is my code,but mails are not sending,please not that email field in my db is clinicemail . Following is my code in clinic controller
public function storeClinics(Request $request)
{
$postdata = $request->all();
$api_key = Str::random(16);
$checkApiKey = Clinic::where('api_key', $api_key)->first();
if(!empty($checkApiKey)) {
$api_key = Str::random(16);
}
$clinic = new Clinic;
$clinic->clinicName=$postdata['user_name'];
$clinic->clinicFname=$postdata['contact_fname'];
$clinic->clinicLname=$postdata['contact_sname'];
$clinic->clinicAddress=$postdata['contact_address'];
$clinic->clinicCity=$postdata['contact_city'];
$clinic->clinicState=$postdata['contact_state'];
$clinic->clinicZip=$postdata['zip'];
$clinic->clinicEmail=$postdata['email'];
$clinic->clinicPhone=$postdata['phone'];
$clinic->clinicURL=$postdata['clinic_website'];
$clinic->clinicPub="no";
$clinic->api_key=$api_key;
$clinic->save();
Notification::route('mail', $clinic->clinicEmail)->notify(new ClinicRegisteredNotification($clinic));
return redirect('clinics');
}
I have also created a notification named ClinicRegisteredNotification in notificcations folder and following is code
<?php
namespace App\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class ClinicRegisteredNotification extends Notification {
public function __construct($clinic) {
$this->user = $clinic;
}
public function via($notifiable) {
return ['mail'];
}
public function toMail($notifiable) {
return (new MailMessage)
->success()
->subject('Welcome')
->line('Dear ' . $this->clinic->clinicName . ', we are happy to see you here.')
->line('Please tell your friends about us.');
}
}
In the ClinicRegisteredNotification, try to add a protected attribute before the __construct($clinic) method and change the line in the constructor.
The beginning of ClinicRegisteredNotification should be this:
class ClinicRegisteredNotification extends Notification {
protected $clinic;
public function __construct($clinic) {
$this->clinic = $clinic;
}
This should solve the issue.

Send a notification when a record changed in database pivot table laravel 5

I want to send a message to my header (which I think means all views) notification part when a record changes in my pivot table so here is my code
This is client model
public function sellmanlist() {
return $this->belongsToMany('App\User' , 'client_user','client_id');
}
This is client controller to save sellman list
public function assignsellman(Client $client) {
$user = User::all();
$client_list = Client::all();
return view('admin.client.assign',compact('client_list','user'));
}
public function assignsellmanSave(Request $request) {
$user = User::all();
$client_list = Client::all();
$client = Client::with('sellmanlist')->firstOrFail();
$sellman = $request->input('sellman');
$client_name = $request->input('client');
$client->sellmanlist()->attach($sellman,['client_id' =>$client_name]);
return view('admin.client.assign',compact('client_list','user'));
}
now here I want to send a notification to the user that a client is assigned to you in his profile any clue how to do that ?
You need to create notification class for notifying user about client added
php artisan make:notification ClientAdded
after that edit this file which you find in a new folder App\Notifications
namespace App\Notifications;
use Illuminate\Notifications\Notification;
class ClientAdded extends Notification
{
protected $client;
public function __construct($client)
{
$this->client = $client;
}
public function via($notifiable)
{
return ['database']; //need to create notifications table check the below link
}
public function toArray($notifiable)
{
return [
'client_id' => $this->client->id,
'client_name' => $this->client->name,
];
}
}
Add below code in your User model and be sure your User model should have used Notifiable trait
public function sendClientAddedNotification($client)
{
$this->notify(new ClientAdded($client));
}
Import these class to User model
use App\Notifications\ClientAdded;
use Illuminate\Notifications\Notifiable;
Now in controller after client saved
$user->sendClientAddedNotification($client);
Here the $user should be the user whom you want to notify
Check this for Database notification https://laravel.com/docs/5.6/notifications#database-notifications

Laravel | Passing variable in Notify

I want to send a mail to Notify, it works but when I try to put the variables, It returns that they are undefined. I don't understand how to pass a variable to Notify, I tried to do ->withResult($result) but it didn't work out.
Here is the controller:
$result = Review::where('user_hash', '=', $data['lname_c'])->where('email', $data['email_c'])->orderBy('created_at', 'desc')->first();
$result->notify(new SendReview());
And my SendReview.php notifications:
public function toMail($notifiable)
{
return $result['invitation_id']; // test to check if variable is passed
return (new MailMessage)
->line('Test.')
->action('Nani', url($url))
->line('Thank you');
}
There is user_hash and invitation_id in my Review table, I want to pass them to the notify. When I do return $result['invitation_id']; it works. Hope I am understandable, I checked for duplicate questions and couldn't find one.
This is how they do it in docs.
$arr = [ 'foo' => "bar" ];
$result->notify(new SendReview($arr));
And in your SendReview.php
...
protected $arr;
public function __construct(array $arr) {
$this->arr = $arr;
}
public function toMail($notifiable) {
// Access your array in here
dd($this->arr);
}
You must use $notifiable variable in your Notification class.
It is an instance of the class to which the notification is being sent. So here your review object is passed as $notifiable variable.
You can try to log it as logger($notifiable) in toMail() method and check its properties.
For people interested in passing an object e.g $msg_recipient and sending an email to a specific user from a controller.
Controller:
Remember to add use Illuminate\Support\Facades\Notification;
Notification::route('mail',$msg_recipient->email)
->notify(new MsgReceived($msg_recipient));
In your notification __construct
public function __construct($msg_recipient)
{
$this->username = $msg_recipient->username;
}
toMail function
public function toMail($notifiable)
{
$username = $this->username;
return (new MailMessage)
->greeting('Hello, '.$username)
->line('You received a brand new msg!')
->action('View msg', url('/'.$username));
}

Arguement 1 must be instance of Illuminate\Http\Request integer given

When I am trying to send mail, everytime a new member is added to the user table, so that they can get a setup password link. I have been trying to get this to work but seem not to be.
public function store(AddUser $request)
{
$user = $request->all();
$user['activate'] = $this->active();
$user['guid'] = $this->guid();
$user['accountno'] = $this->generateAndValidateAccountno();
$check = User::find($user['phone']);
if(!$check) {
$id = User::create($user);
$this->sendEmail($user['accountno']);
}
return redirect('employee');
}
public function sendEmail(Request $request, $id)
{
$user = User::find($id);
Beautymail::send('emails.welcome', [], function($message)
{
$message
->to('$id->email', '$id->fname')
->subject('Welcome!');
});
}
}
Not sure what am doing wrong
Just use the same request class in the controller and the model. In your user model, add use Illuminate\Http\Request at the top of the class to tell it which Request class to use.
Just change:
public function sendEmail(Request $request, $id){...}
to
public function sendEmail($id){...}

Categories