Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Laravel Eloquent Model observer events return the object?

For example

namespace App\Observers;

use App\Models\User;

class UserObserver
{

    public function saving(User $user)
    {
        $user->epoch = time();

        $user->save(); // or even this
        return $user; // should I do this or not?
    }    
}

I cannot find any good documentation about the model events when they are called and what to put inside it.

like image 552
online Thomas Avatar asked Oct 11 '25 09:10

online Thomas


1 Answers

The laravel model events available are theses :

retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored

the ed ones are called once the event is over the ing one are called just before the event is launch

exemple :

creating will affect your model before getting created (object not in database yet, so no id) created, is called after it as been create into the database (you can get his id)

when you are using this:

$model->save();

you can think like this :

$model->saving(do something)->save(); $model->save()->saved();

like image 60
Mathieu Ferre Avatar answered Oct 14 '25 00:10

Mathieu Ferre