簡體   English   中英

在 Laravel 5.5 中向用戶發送通知

[英]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 所以有什么問題? 我必須做的。

謝謝

據我所知,您正在執行以下代碼:

  1. $userINList變量中有一個名稱數組
  2. 您遍歷數組中的每個名稱
  3. 刪除名稱中的所有空格
  4. 檢索每個User
  5. 遍歷每個User
  6. 刪除User名中的所有空格
  7. 比較2個名字
  8. 如果比較通過,則將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM