Home > Back-end >  how to send mail to all users when new post data is entered in database in laravel 8
how to send mail to all users when new post data is entered in database in laravel 8

Time:02-27

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

CodePudding user response:

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

CodePudding user response:

<?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));
      }
}
  • Related