withoutEvents函式裡面的事件被觸發

Yoger發表於2020-09-08

描述:

Version: Laravel Framework 7.26.1
在呼叫withoutEvents() 後,Model中的儲存事件仍然被觸發。

安裝專案

composer create-project –prefer-dist laravel/laravel blog

建立一個Model

<?php

namespace App;
use App\Events\UserSavedEvent;
use Illuminate\Database\Eloquent\Model;

class TestModel extends Model
{
    public $table = 'users';

    protected $dispatchesEvents = [
        'saved' => UserSavedEvent::class,
    ];
}

建立Event

<?php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UserSavedEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct()
    {
        dd('UserSavedEvent');
    }

}

測試用例

Route::get('/', function () {
    TestModel::withoutEvents(function () {
        $user = TestModel::first();
        $user->save();
    });
    return view('welcome');
});

結果

withoutEvents中的saved事件被觸發;

withoutEvents函式裡面的事件被觸發

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章