How to send message to several specific users Laravel Notification? - laravel

I studied the Laraval.s notifications. I can not realize how to send bulk notifications to the specific users. I know their ids.
Should I use private channel or broadcast?

in laravel there are two way to send notificatons
$user=User::find(1) ;
$users=User::all() ;
$user->notify(new InvoicePaid($invoice))
// or
Notification::send($users,new InvoicePaid($invoice))
so both ways send only one notification but we can send it to single or multiple users.
if you need to send multiple notifications to multiple users you should use loops:
$notifications=[new InvoicePaid($invoice) ]
foreach($notifications as $notification)
{
Notification::send($users,$notification)
}
also there is a better way to handle this.you can use event and it is better to use event to send notification or perform other task after a specific action. for example define a event as userRegisterd. then you can assign one or more listener to this event like sendNewUserNotification , congratulationsNotification.
in each listener notify the users

Related

Slack API: How to send a scheduled private message to every member in the channel?

I want to send a weekly private message to all channel members.
I'm using currently using app.event('app_home_opened') to do such a thing. But I want the open rate to be higher, and that's why I want the bot to send the message automatically.
chat.scheduleMessage works perfectly but I have to pass a channel id as a parameter, meaning that only 1 person will receive the message.
How can I achieve what chat.scheduleMessage does, but for every single member?
According to my search and knowledge I think with slackapi we can send message only one channel at a time..
But I think if you implement like this then you can send messages to multiple channel
Steps:
add all channel in one array and apply loop , then one by one channel id will pass and message will send to all channel. If you want to different channel messages to all channel then you can also add messages in channel array
Hope you got solution

Laravel Events Dynamic Channel Name

I am creating a real-time notifications feature within my app that will use Pusher to automatically notify the user when they get a notification (which is created by certain actions taken by users they follow).
I know how to set up the event and have it broadcast, but I'm confused as to the channels to broadcast these notifications on. The situation will be user A follows many other users, but also has many followers himself.
If user A posts new content, we can trigger an event that broadcasts a notification to all of his followers that he just posted something. The question here is, do we broadcast this channel on "user.A"? That means every other user that follows user A will have to subscribe to that channel all the time along with the channels of every other user they follow.
So, what's more efficient, to dynamically broadcast across possibly hundreds of different channels (each channel representing one of user A's followers) OR should each user automatically listen to the channels of possibly hundreds of different users?
Not sure which is more efficient. Thanks!

To prevent timeout - what are the advantages of queueing a job vs chunking results?

My Laravel 5 site allows users to send emails to their contacts. My problem is that the operation times out after it loops through around 50 contacts.
An overview of my process:
Get the list of contacts
Construct an email
Loop through the list of contacts and send them each an email using a mailer service.
return email details to the controller to be saved in the db.
Chunking is pretty easy to understand, but I'm not real comfortable with the mechanics of placing a job on a queue.
To prevent the timeout, would I be better off chunking the contacts to limit the size of the loop or putting the entire job on a queue? If the entire job should be placed on a queue - can I still chunk contacts? Can a queued job still use mail::queue or is that just redundant?
Loop Code:
public function sendIndividualEmail($members, $subject, $body, $file)
{
$view = 'emails.memberMessage';
//construct email details
$mData = $this->emailConstructor($subject, $body);
//check to see if there is an attachment, if so upload it.
if (!is_null($file)){
$uploadedFile = $this->attachment->saveAttachment($file);
$mData['path'] = 'https://'.$_SERVER["HTTP_HOST"].'/uploads/attachments/'.$uploadedFile['filename'];
$mData['display'] = $uploadedFile['display'];
}
foreach($members as $member){
if (!empty($member->contact_email)){
//add member details here
$mData['email'] = $member->contact_email;
$mData['name'] = $member->contact_firstName;
//email member
$this->emailTo($view, $mData);
$mData['emailCount']++;
}
}
return $mData;
}
Mailer Service:
public function emailTo($view, $mData)
{
Mail::queue($view, $mData, function($message) use ($mData)
{
$message->from($mData['from'], $mData['fromName']);
$message->to($mData['email'], $mData['name'])->subject($mData['subject']);
$message->getHeaders()->addTextHeader('X-MC-Metadata', $mData['meta']);
if(array_key_exists('path', $mData)){
$message->attach($mData['path'], array('as' => $mData['display']));
}
});
}
A few suggestions first.
Chunking them would use less computational power, but does not offer the flexibility that a queue system presents.
Chunking scenario ---
Get All Models, for count(x) as new chunk store chunk.
Foreach chunk as items
foreach item in items
item->doSomething
-- Pagination
I might adapt the pagination library to support this instead.
I.E get a collection and paginate it, store the page number, and just do a page worth of records at a time?
-- Event Observer Queue?
Another technique would be to use the event listener system.
You can to this a number of ways, just think about when an email should be sent.
Your model would have either a column like sent_mymail_email, or you could use a mutator getSentMymailEmailAttribute() to return a boolean value of true if the email was sent (job is complete).
You would then set up a new event or latch on to an existing event.
see: How Can I See All Laravel Events Being Fired
Queue system --
A queue system would receive events and data from one server via http request . The items are then added to a big list of jobs that need to be completed. When the event comes up (it's turn), it will send a http request to somewhere on your system. Your system then interprets what the task is and accomplishes the task, when complete, a response is sent back to the queue system(typically) notifying the system of a completed task. The queue will then move on to the next task, send the request ... and so on.
Comparing this to the chunk method, you can see that your application needs to send the email in both scenarios, however it does not need to send the task, receive the task or interpret what the task is in the chunking method.
You also have less moving parts in the chunking method, however if you wanted the ability to scale and put part of your applications workload onto a secondary system or cluster to handle the jobs, you would want to go with the queue system.
The queue system depends on 3rd party services that have their own built in flaws. For example you cant define an order for these items.
This blog post explains:
http://cloudstacking.com/posts/amazon-sqs-gotchas.html
Here is another decent post about using queue systems:
http://www.isixsigma.com/industries/retail/queuing-theory-and-practice-source-competitive-advantage/
The advantage in a nutshell primarily being that you have the ability to scale to a very large amount of these requests being processed with zero impact on your front-end(application).
You can run these jobs on a separate system or cluster of systems to push the work that is needed to a server that does not impact user experience.
You are able to queue the entire job and still queue the mail, I do that in my application and don't feel it is redundant. It allows you to break up the processing into logical steps that can be completed independent of one another. For example the job can continue processing the contacts and scheduling the emails without needing to wait for them to send.
While I haven't done it myself, I believe you are able to chunk the contacts and still use a queue on the job.

Parse.com Send push notifications to concrete devices

According to this document
I can send push notification to 'installations' using channels or query.
But how can I send notification to concrete installations/devices by their installationId?
For example I have 20 device and have their installationId and I want to send push to those 20 devices.
Thanks.
In your circumstance you dont want to restrict fields by including a parameter. In other words, since you want to send a push notification to all users then you don't include any parameters. So in short, simply create an unbiased push payload with a title and description and then execute it for whatever deviceType you specify or need

Filtering socket.io subscriptions

Imagine I have a User model and also a Message model. User has many messages.
Then in the client I do a:
io.socket.get('/user/2/messages'....
I get all my user messages and there is no problem trying to get someones else messages because I have a policy for that. Good.
I want to listen if the user has new messages, if I do a:
io.socket.on('message')
I get every message created, mine or not mine.
So: Can I listen just for MY messages? AKA listen for associated messages but not all of them.
Maybe using a policy or something for just that. Because even if there is a way to listen to them, anyone can modify the client to listen to what he wants to, I need to filter all of that.
Yes, you can. The trick is to listen for user events with the "addedTo" verb, rather than listening directly for message creation. The code would be something like:
io.socket.on('user', function(msg) {
if (msg.verb == 'addedTo' && msg.attribute == 'messages') {
// A new message was added to the user's "messages" collection
var messageId = msg.addedId
// From here you can request /message/[messageId] to get the
// message details if you need them
}
});
More info on the .publishAdd() doc page.
Note that only the ID of the added message is given; you may find you want the whole thing. You can handle that by either making a separate request for the new message, or overriding publishAdd as is suggested in this answer.
The only catch here is to make sure you're limiting who gets subscribed to those user events. It sounds like you have a policy in place that prevents users from accessing /user/:id/messages for other users. You'll want want preventing them from accessing /user/:id for other users as well (at least via sockets), since they will be subscribed to any user they access that way.
If this is undesirable--that is, if you'd like people to be able to hit those routes--then an alternative would be to use the autoSubscribe model property to restrict the automatic subscription that blueprints normally do. autoSubscribe is normally set to true, which means that any time a socket request is made for a model, the requesting socket will be subscribed to all events for that model instance. You can instead set it to an array of contexts that should be subscribed to. Contexts are specific events you're interested in, like update or destroy (more about contexts in the docs). Finally, you can set autoSubscribe to false to restrict subscription to that model entirely. Then you can just subscribe manually with .subscribe() whenever you want to listen for events.
You can see some examples of contexts and autoSubscribe in action in the sailsChat sample app.

Resources