Access individual data in a collection passing to Notification method - laravel

I have queried a list of users based on a filter to send out notifications and i want to use this collection method to send out the notification.
Collection method
As in the documentation i pass the users collection to the notification and my post data
Notification::send($users, new PostAlert($post));
I believe, this collection method is firing notifications in a loop. One-by-one.If it is, how do i access a user's details inside the notification ? i can only access $post details for now
Notification::send($users, new PostAlert($users, $post));
Doing the above passes the collection and i cannot access a single user detail inside the notification.
I know that i can set the firing on a loop, but i believe it is not the cleanest way
foreach($users as $user)
{
Notification::send(new PostAlert($user, $post));
}
It would be very helpful if you could help me how would i access a single model passing from collection.

It is pretty easy, Try it,
You will find a variable called $notifiable
// PostAlert
...
// toMail() or toArray()
public function toMail($notifiable)
{
dd($notifiable,"the user laravel is sending to.");
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
...
Happy Codding.

Related

refresh page after updated model - Laravel

I want to refresh current page after any user update
I'm trying to do something like that in User Model :
public static function boot()
{
self::updated(function ($model) {
return back(); //or redirect(Request::url())
});
}
but it wasn't working.
How can I refresh the page if any user updated
In general, the model event functions creating/created/updating/updating/saved/saving should only ever return false or nothing (void). Returning false in for instance updating (that is: before the model is persisted in the database) cancels the model update (this works for all propagating events, see https://laravel.com/docs/9.x/events#stopping-the-propagation-of-an-event).
To "refresh" the current page after a user update, you have to be more specific about what you require. The back() function that you use (or the aliases redirect()->back() or even app('redirect')->back()) is (to my knowledge) to be used in controllers and it uses the Referer header or a property in the user's session to determine to which page to send the client to. This is most often used with validation errors, so that you can send the user back to the page they came from along with any possible validation error messages.
Using back() (or any other request completions like return response()->json('mydata')) inside events is wrong and it doesn't even work since the result of such events is not being used to complete the request. The only valid thing you "could" do is to try validation inside an event, which in turn could throw ValidationExceptions and is therefore automatically handled.
What you should do is use the controller method that actually handles the request that updates the user:
// UserController.php
/** (PUT) Update a user */
public function update(Request $request, User $user)
{
if($user->update($this->validate($request, [/* validations */])) {
return redirect()->back();
// or even be explicit and use `return redirect()->route('users.show', $user);`
}
// `update()` returned false, meaning one of the model events returned `false`
// (there is no exception thrown here).
session()->flash('alert-info', 'Something went wrong');
return redirect()->back();
}

way to insert a new record, with cashier subscription?

I am searching the web today to see if I can somehow be able to add a new record to some tables whenever the user memberships renew.
let's say we have an app have (users, notifications, subscriptions ) tabes.
when he subscribe the first time, I can add a new record in notification table within the same controller, but what if I want every time he renews his subscription a new instance can be added in the notification table?
Eloquent Model Event
is the way to go, I believe.
Or if the logic is really simple, you can define it in your model class.
/**
* The "booting" method of the model.
*
* #param Builder
*/
protected static function boot()
{
parent::boot();
static::updated(function (Subscription $subscription) {
// your subscription logic here...
});
}

Send SMS from laravel?

I have created a notification class called Test. When I called this class from here $user->notify(new Test($user,$password,$message)); which method is called?.
I want to send SMS but inside that, it has a predefined method called
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
should I create another function for sending SMS? and how can I do that?
because I want to send an SMS to a URL something like this
$url='URL.php?USER=aaaa&PWD=bbbb&MASK=cccc&NUM='07453727272''&MSG='This is a message';
Inside your class there is a via method which is an array, returning, in your case. Mail. You may want to change that to 'nexmo' for example.
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['nexmo'];
}
The via method receives a $notifiable instance, which will be an
instance of the class to which the notification is being sent. You may
use $notifiable to determine which channels the notification should be
delivered on:
Depending on the Gateway you are using for SMS there may be a specific notification which applies already: (see left hand navigation)
https://laravel-notification-channels.com/clickatell/
If you need a custom one, you should be able to follow the examples of some of the notifications channels already built to create your own. I'd add the specific SMS gateway you are using for clarity to see if I can provide additional information.

Laravel notification email change title

I`m trying to send email notification.
When my emails sent the title is 'Example'.
How can i change the title by toMail() method of Notification class.
public function toMail($notifiable)
{
return (new MailMessage)
->greeting($this->notifMessage['subject'])
->line($this->notifMessage['description']);
}
my code is here.
Thank you! Best regards.
You can change the config/mail.php 'from' field to match your need, however i would advice against doing so, im not saying this is the case but lets imagine you have two different senders, changing the config only allows one sender per website.
So the easy solution is to override the 'from' fields in the toMail() function itself, this way you can have as many senders as you want.
Just add
->from('some_adress','some_name')
to your code.
You can easaly do:
public function toMail($notifiable)
{
return (new MailMessage)
// other options
->from("An amazing sender")
->subject("Amazing email's subject");
}

Why can't this method access the session?

I have a session containing some data that I access throughout several methods in my controller with no trouble. But one method in particular has problems.
I have made a little booking system. On completion of a booking, I call a function to send an e-mail to myself and the customer:
public function complete(Request $request)
{
$details = Session::get('details');
// send emails: call sendConfirmationEmail(to address, using this view)
$this->sendConfirmationEmail(env('EMAIL'), 'emails.ourconfirmation');
$this->sendConfirmationEmail($details->booker_email, 'emails.bookerconfirmation');
return view('booking/complete');
}
private function sendConfirmationEmail($to,$view)
{
$from = env('OFFICE_EMAIL');
$to_address = $to;
$details = Session::get('details');
$instance = Session::get('instance');
Mail::queue($view, compact(['details','instance']), function($message) use ($to){
$message->from(env('OFFICE_EMAIL'))
->to($to)
->subject('Thanks for booking');
});
}
First I got an error accessing a non-object in my e-mail view. So to test it I just set the sendConfirmationEmail function to return $instance - blank page. Then I tested it by commenting out the function call in complete() and returning $instance there. No problem, there's a nice shiny session full of data. Then I tried passing $instance from complete() to sendConfirmationEmail() and returning it: again, blank page. Why can't sendConfirmationEmail 'see' my session?!
To my knowledge, Sessions are for using across HTTP requests, not across functions in PHP. You are trying the use Sessions as global variables.
You can simply capture details and instance session data in the complete function, and then pass them along as parameters for the sendConfirmationEmail() function.

Resources