Send SMS from laravel? - 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.

Related

Laravel broadcasting - use job ID as an 'order' property

I want to send some sort of (unique, auto-incrementing) number as part of the payload of an event - so that the consumer can, for example, know it should ignore an 'updated' event if the event is older than a previous 'update' event it received.
I see I can add a broadcastWith method to my event, where I could add such a number, which I'm storing in some table.
But, I don't really need to create a new number. The ID of the job in the jobs table will work just fine. So, how can I make Laravel automatically add a property, say order, to this event before it is broadcast and make the value of order to id column from the jobs table? Is there a way to get it in the broadcastWith method?
I had previously thought of using a timestamp as the 'order' but of course that won't help me or the consumer when two events have been created in a short-a timeframe as a computer can create two events.
UPDATE
Looks like I haven't worded it well and people are confused as to what I'm looking for. In hindsight, I shouldn't of added the criteria that it must be the job id that gets included in the payload. The main thing I'm after is a unique, auto-incrementing ID in each broadcast event. For example, I have an UserUpdated event. Say the a user is updated twice - my SPA that is consuming the events needs to know which event is the newer one, otherwise the SPA might display outdated info. If the events are delivered sequentially, then this problem won't happen. But, especially as I'm relying on a third-party service (Pusher) to deliver the events to the SPA, I don't want to assume / trust that the events will always be delivered in the same order they were sent to Pusher.
Hi such a nice requirement, i have been working on a POCO and here are some snippets, you do not need broadcast at all. Of course you need to have the queue worker up and running
Running The Queue Worker
On your order controller, i guess you need the update method to dispatch the job before commiting.
function update(Request $req)
{
$data= Order::find($req->id);
$data->amount=$req->amount; //example field
PostUpdateOrderJob::dispatch($data)->beforeCommit();
$data->save();
}
Important: Why before commit and not after commit: Setting the after_commit configuration option to true will also cause any queued event listeners, mailables, notifications, and broadcast events to be dispatched after all open database transactions have been committed.
Your PostUpdateOrderJob class
?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Order;
use Throwable;
class PostUpdateOrderJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of times the job may be attempted.
*
* #var int
*/
public $tries = 25;
/**
* The maximum number of unhandled exceptions to allow before failing.
*
* #var int
*/
public $maxExceptions = 3;
protected $order;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(Order $order)
{
$this->order=$order;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$this->order->update(['jobid'=>$this->job->getJobId()]);
}
public function failed(Throwable $exception)
{
// Send user notification of failure, etc...
//Several options on link below
//https://laravel.com/docs/9.x/queues#dealing-with-failed-jobs
}
}
Well php has a function called time() which returns the current unix time in seconds, so you can just use that in your broadcast event.
In your broadcast event, you can add this time to the public class properties, which would then be available through the event payload:
class MyBroadcastEvent implements ShouldBroadcast
{
public $time;
public function __construct()
{
$this->time = time();
}
}
I'm not sure if this is exactly what you need, your question is kind of confusing to be honest.

Laravel 8 Mail Notifications

I'm using Laravel 8, and my Client asks to be able to modify the mailables content.
I need to show the different notification templates, and let the users add text, action buttons, etc.
I'm thinking on building a DB structure to store the different fields with the corresponding order, but I'm not sure if it is possible to apply that on the toMail method.
For example: a NotificationTemplate Model that hasMany NotificationField (this can have type and content).
And then try to use it as a query builder:
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$fields = NotificationTemplate::where('name', 'example')->fields;
$mail = (new MailMessage);
foreach($fields as $field){
if($field->$type = 'line'){
$mail->line($field->content);
}
}
return $mail;
}
Is this possible? Or is there another way to allow the admins of a Laravel 8 app to modify the Mail notificiation message from the frontend?
Thanks, HernĂ¡n.
You can simply give the admin a textarea where he can customize the content of email.
I use this package armincms/option to stock the content and in your template email you can use option()->content

Access individual data in a collection passing to Notification method

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.

Slack Laravel Formatting

So notifications work no problems, on my user model i am routing to slack as such:
/**
* Route notifications for the Slack channel.
*
* #return string
*/
public function routeNotificationForSlack()
{
return env('SLACK_WEBHOOK_URL');
}
However when it comes time to make changes, the following from and to methods have no effect.
return (new SlackMessage)
->from('Ghost', ':ghost:')
->to('#channel-name')
What do i need to do to post to another channel? and change the from would be nice!

how to intercept graphql request in api-platform?

i'm using api-platform 2.3.5 and i can't find a way to intercept a graphQl request.
I mean that let's say i'm making a mutation (update) and want to also log the data or send an email. How do i do that ?
I did read the api-platform documentation, but there's very little about their implementation of graphQl. It does quite a lot automagically.
Events are not yet implemented (https://github.com/api-platform/core/pull/2329)
I also found this - https://github.com/api-platform/core/blob/master/src/GraphQl/Resolver/Factory/ItemMutationResolverFactory.php#L101
but i'd rather not touch it. Is there a simpler way ?
I know this is a bit old but if only for reference.
The recommended way with API-Platform's graphql is to use stage. See this documentation.
In the case of the sending an e-mail you can use the serialize stage. See example below for sending email to notify user he has received a message.
<?php
namespace App\Stage;
use ApiPlatform\Core\GraphQl\Resolver\Stage\SerializeStageInterface;
use App\Email\Mailer;
final class SerializeStage implements SerializeStageInterface
{
/**
* #var Mailer
*/
private $mailer;
private $serializeStage;
public function __construct(
SerializeStageInterface $serializeStage,
Mailer $mailer)
{
$this->serializeStage = $serializeStage;
$this->mailer = $mailer;
}
/**
* #param object|iterable|null $itemOrCollection
*/
public function __invoke($itemOrCollection, string $resourceClass, string $operationName, array $context): ?array
{
// Call the decorated serialized stage (this syntax calls the __invoke method).
$serializedObject = ($this->serializeStage)($itemOrCollection, $resourceClass, $operationName, $context);
// send notification e-mail if creating message
if ($resourceClass === 'App\Entity\Message' && $operationName === 'create') {
$this->mailer->sendMessageNotificationEmail($itemOrCollection->getReceiver());
}
return $serializedObject;
}
}
Then we need to decorate the native stage:
/config/services.yaml
App\Stage\SerializeStage:
decorates: api_platform.graphql.resolver.stage.serialize

Resources