2017-08-01 87 views
1

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

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

UPDATE:

由于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)); 
+0

你如何识别管理员?在'users'表上是否有'is_admin'这样的属性,还是通过关系来完成? –

+0

我已经使用委托的角色和权限。我可以得到管理员,但不知道如何传递($ assign_to,$ admin) – Ja22

回答

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

+0

感谢您的回复。我会在今天检查并通知您 – Ja22

+1

您的解决方案正常工作。我做了一个小修改,只是通过角色获取用户。谢谢您的帮助。干杯 – Ja22