问题
Merry Christmas guys!
I am new to Laravel. Just had a beginner's question, when I am trying to use service provider and model event to log the update information.
Was following the online doc: https://laravel.com/docs/5.3/eloquent#events
After put all code together, I find that the model event only fire when create the use but never log anything when I edit the user.
Did I miss anything? Feel like the $user didn't get assigned properly. Where is it from? from other service provider?
Any explanation or hint will be appreciated!
<?php
namespace App\Providers;
use App\User;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
User::creating(function ($user) {
Log::info('event creating');
});
User::created(function ($user) {
Log::info('event created');
});
User::updating(function ($user) {
Log::info('event updating');
});
User::updated(function ($user) {
Log::info('event updated');
});
User::saving(function ($user) {
Log::info('event saving');
});
User::saved(function ($user) {
Log::info('event saved');
});
User::deleting(function ($user) {
Log::info('event deleting');
});
User::deleted(function ($user) {
Log::info('event deleted');
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
回答1:
You need to retrieve the user from the database and then save that user in order to fire the event. For example:
This will NOT fire the update event:
User::where('id', $id)->update(['username' => $newUsername]);
This will fire the update event:
User::find($id)->update(['username' => $newUsername]);
回答2:
Possible reasons:
The row is not updated at all - no changes. Hence not firing, and
You used
update
. Check the docs here: https://laravel.com/docs/5.3/eloquent#updates
When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.
来源:https://stackoverflow.com/questions/41295032/laravel-eloquent-model-update-event-is-not-fired