Reputation: 75
i want to send all users notification when a user create a new post in database the notification should go to all the users as new post created
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use App\Notifications\PostNotificationforAll;
class Postnotification extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'post:notification';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Post notification for all users';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$users= User::all();
foreach ($users as $user) {
$user->notify(new PostNotificationforAll());
}
}
}
can any help me out what condition should i use
Upvotes: 1
Views: 1431
Reputation: 21
You can do it with creating a new mail class
php artisan make:mail NotifyUsers
Then make a mail.blade.php have your html template mail which send to users with $user : is a user name who created a post , and $post_title : is a title of the post created
=> In Mail/NotifyUsers
class NotifyUsers extends Mailable
{
use Queueable, SerializesModels;
public $user,$post_title;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($user,$post_title)
{
$this->user = $user;
$this->post_title = $post_title;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.mail')->with(['user' => $user , 'post_title' => $post_title]);
}
}
Then go to controller which have a store posts function and put this code
foreach (User::all('email') as $email) {
Mail::to($email)->send(new NotifyUsers(auth()->user()->name , $request->post_title));
}
Upvotes: 0
Reputation: 366
<?php
namespace App\Observers;
use App\Models\Post;
use App\Models\User;
class PostObserver
{
public function created(Post $post)
{
$users = User::where(...)->get();
// Send the notifications
Notification::send($users, new Postnotification($post));
}
}
Upvotes: 0
Reputation: 331
You can do it using observer When new post created you can run event using observer class
<?php
namespace App\Observers;
use App\Models\Post;
class PostObserver
{
/**
* Handle the Rate "created" event.
*
* @param Post $post
* @return void
*/
public function created(Post $post)
{
event(new PostCreated($post));
}
}
The in PostCreated event you can listen to it then in listener you can notifiy users with this post
You can read more about observer from laravel docs
Upvotes: 2