2017-08-01 79 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