Laravel 5.3发送数据库通知

时间:2017-08-01 12:03:23

标签: laravel notifications laravel-5.3

adminuser添加新约会时,应为所有admins以及分配的user创建数据库通知。在查看通知时,所有admins应该会看到所有通知,而用户只能看到为其分配的通知。

public function submitAppointmentForm(Request $request){

    $validator = Validator::make($request->all(), [
        'respond' => 'required',
        'user2_status' => 'required',
    ]);

    if ($validator->fails()) {
        return response()->json(['error'=>$validator->errors()->all()]);
    }
    else
    {
        $user = Auth::user();

        $appointment = new Appointments();
        $appointment->project_list_id = $request->project_id;
        $appointment->respond = $request->respond;
        $appointment->user2_status = $request->user2_status;
        $appointment->date = $request->appointment_date;
        $appointment->assigned_to = $request->assign_to;
        $appointment->user2_note = $request->user2_note;

        $appointment->assigned_by = $user->user_id;
        $appointment->added_by = $user->user_id;
        $appointment->save();

        $assign_to = User::where('user_id', $request->assign_to)->first();

        Notification::send($assign_to, new NewAppointmentNotification($request));

        return response()->json(['success'=>'Successfully added']);
    } 
}

仅为已分配的user添加上述代码通知。不适用于admins

如何在发送通知时添加管理员

Notification::send($assign_to, new NewAppointmentNotification($request));

更新:

感谢Dees Oomens我按照我的要求进行了一次小修改

$assign_to = User::where('user_id', $request->assign_to)->first();

$users = User::whereHas('roles', function($q){
                $q->where('name', 'admin');
            })->get();

$users->push($assign_to);

Notification::send($users, new NewAppointmentNotification($request));

1 个答案:

答案 0 :(得分:2)

首先,您需要获得所有管理员。你使用委托,所以我不确定你用过什么角色,但最好的猜测是:

$users = User::with(['roles' => function($query) {
    $query->where('name', 'admin');
}])->where('id', '!=', $user->id)->get();

$users->push($assign_to);

Notification::send($users, new NewAppointmentNotification($request));

现在$users数组中的所有用户都会收到通知。 $users数组包含所有管理员(但不包括当前经过身份验证的管理员)和$assign_to用户。