Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save NOW() to the same field in my Laravel Eloquent model every time I save?

Every time I perform the following:

$user = new User;
$user->name = 'John';
$user->save();

I want a field called "modified" to be updated to NOW() in MySQL. I can't use Laravel's timestamps because I'm only using a single modified field. I could rely on MySQL to do this for me, but I was wondering if there was a way to accomplish this in my Laravel model? Perhaps using a mutator in some way to set this before saving?

As a bonus: how would I do something like this $user->modified = "NOW()"? (which is obviously wrong, but hopefully demonstrates the point)

like image 436
prograhammer Avatar asked Jan 27 '15 01:01

prograhammer


People also ask

How do I save multiple records in Laravel eloquent?

Sometimes you might need to save multiple records at once and you can do so by using the "saveMany()" method or the "createMany()" method available to each of the Eloquent model relation. Do note that you need to have "hasMany()" relationship in order to do so.

What is Save () in Laravel?

save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database.

How do I save a model in Laravel?

To quietly save a model in Laravel you can make use of the "saveQuietly" method available to each model instance. ->saveQuietly();

What is fillable in Laravel model?

The fillable property is used inside the model. It takes care of defining which fields are to be considered when the user will insert or update data. Only the fields marked as fillable are used in the mass assignment. This is done to avoid mass assignment data attacks when the user sends data from the HTTP request.


1 Answers

You can accomplish this in the saving event, for which you can register a callback in you model's boot method:

class User extends Eloquent {

    public static function boot()
    {
        static::saving(function($user)
        {
            $user->modified = DB::raw('NOW()');

            // Alternatively, you can use this:
            $user->modified = Carbon\Carbon::now();
        });

        parent::boot();
    }

}
like image 160
Joseph Silber Avatar answered Oct 12 '22 08:10

Joseph Silber