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)
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.
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.
To quietly save a model in Laravel you can make use of the "saveQuietly" method available to each model instance. ->saveQuietly();
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With