Monday, April 18, 2022

[FIXED] how to send mail to all users when new post data is entered in database in laravel 8

Issue

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


Solution

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


Answered By - Jahongir Tursunboyev
Answer Checked By - Timothy Miller (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.