[英]Send a notification to user in Laravel 5.5
這就是場景。 我有用戶 A 通過通知發送給其他用戶 B、C、D...加入一個組的請求。 所以在 laravel 中,我創建了遷移和控制器來處理通知。
這是 GroupController 的代碼
...
foreach ($userINList as $userIN) {
$userIN = str_replace(' ', '', $userIN);
$userDBList = User::all();
foreach ($userDBList as $userDB) {
$name = $userDB->last_name . $userDB->first_name;
$name = str_replace(' ', '', $name);
if (strcmp($name, $userIN) == 0) {
$newGroup->users()->attach($userDB->id, ['role' => 'member', 'state' => 'pending']);
$notification = User::find($userIN->id);
$notification->notify(new GroupNotification($newGroup));
}
}
}
...
因此,在$notification
我將嘗試傳遞收到邀請的用戶的 id,然后使用 notify() 方法發送通知,但是在用戶 A 創建組后,沒有向用戶 B、C 發送通知, D... 我已經在組模型中包含了use Notifiable
。 所以有什么問題? 我必須做的。
謝謝
據我所知,您正在執行以下代碼:
$userINList
變量中有一個名稱數組User
User
User
名中的所有空格User
添加到組並發送通知我們可以在這里進行很多改進。 例如,我們已經知道您希望通知哪些用戶,因此您無需獲取和比較所有用戶。
首先, $userINList
要么是一個數組User
對象或數組User
id
的S -數組User
對象是更好的。 然后你可以簡單地遍歷每一個。
例如,如果你有一個 id 數組,那么你可以這樣做:
$group = Group::find(1);
$userINList = [1, 2, 3, 4];
User::whereIn('id', $userINList)
->get()
->each(function ($user) use ($group) {
$group->users()->attach($user->id, [
'role' => 'member',
'state' => 'pending'
]);
$user->notify(new GroupNotification($group));
});
如果你有一個對象數組,那就更容易了,你可以這樣做:
$group = Group::find(1);
collect($users)->each(function ($user) use ($group) {
$group->users()->attach($user->id, [
'role' => 'member',
'state' => 'pending'
]);
$user->notify(new GroupNotification($group));
});
超級簡單:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.