【问题标题】:Send a notification when a record changed in database pivot table laravel 5当数据库数据透视表 laravel 5 中的记录发生更改时发送通知
【发布时间】:2018-07-18 11:17:16
【问题描述】:

当我的数据透视表中的记录发生更改时,我想向我的标题(我认为这意味着所有视图)通知部分发送一条消息,所以这是我的代码

这是客户端模型

public function sellmanlist() {
  return $this->belongsToMany('App\User' , 'client_user','client_id');
}

这是保存卖家列表的客户端控制器

public function assignsellman(Client $client) {
  $user = User::all();
  $client_list = Client::all();
  return view('admin.client.assign',compact('client_list','user'));
}

public function assignsellmanSave(Request $request) {
  $user = User::all();
  $client_list = Client::all();
  $client = Client::with('sellmanlist')->firstOrFail();
  $sellman = $request->input('sellman');
  $client_name = $request->input('client');
  $client->sellmanlist()->attach($sellman,['client_id' =>$client_name]);
  return view('admin.client.assign',compact('client_list','user'));
}

现在我想向用户发送一条通知,告诉他在他的个人资料中为您分配了一个客户,有什么线索吗?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您需要创建通知类来通知用户添加了客户端

    php artisan make:notification ClientAdded
    

    然后编辑您在新文件夹App\Notifications中找到的这个文件

    namespace App\Notifications;
    
    use Illuminate\Notifications\Notification;
    
    class ClientAdded extends Notification
    {
    
        protected $client;
    
        public function __construct($client)
        {
            $this->client = $client;
        }
    
        public function via($notifiable)
        {
            return ['database']; //need to create notifications table check the below link
        }
    
        public function toArray($notifiable)
        {
           return [
                  'client_id' => $this->client->id,
                  'client_name' => $this->client->name,
              ];
        }
    
    }
    

    在您的 User 模型中添加以下代码,并确保您的 User 模型应该使用 Notifiable 特征

    public function sendClientAddedNotification($client)
    {
        $this->notify(new ClientAdded($client));
    }
    

    将这些类导入User模型

    use App\Notifications\ClientAdded;
    use Illuminate\Notifications\Notifiable;
    

    客户端保存后现在在控制器中

    $user->sendClientAddedNotification($client); 
    

    这里的 $user 应该是您要通知的用户

    查看数据库通知 https://laravel.com/docs/5.6/notifications#database-notifications

    【讨论】:

    • 确保$user instance 应该是您要发送通知的用户
    • 当然,让我改一下代码,我们只需要更改通知中的via
    • @Farshad 我已经更新了数据库通知的答案,但是您必须创建一个 notifications 表和一个模型才能访问。我在底部添加了一个链接,检查该链接是否包含创建通知表的详细信息。如果您有任何问题,请告诉我
    • 这是代码$user->sendClientAddedNotification($client);
    猜你喜欢
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    相关资源
    最近更新 更多