Alan
Alan

Reputation: 2639

Laravel not saving a field

I have an application running Laravel 5.3.

I need to make a modification to all records in a table so this is my code:

Car::all()->each(function($car){
    $car->created_by = 10;
    $car->updated_by = 15;
    $car->save();
});

The problem is that the created_by field is being saved properly but updated_by doesn't. Even if I dump($car) previously to the save() line I can see that both fields have been modified. I also added both fields to $fillable (I know, this is for mass assignments but just in case..).

Upvotes: 0

Views: 1358

Answers (2)

Alan
Alan

Reputation: 2639

I found the solution. My model is using a trait that everytime the model is updated it saves who made the update in the updated_by field so since I'm executing from the console through a command the first code I posted, the trait is saving that update action and being that no user is logged auth()->user() returns null and this is what is saved. Hope I made myself clear.

Upvotes: 0

omitobi
omitobi

Reputation: 7334

Rather than retrieve all cars and loop round them and make thousands of query, you can do the mass update in one query:

Car::update(['created_by' => 10, 'updated_by' => 15]);

This is simple, clean, more efficient.

If you need more information, please read through Laravel doc especially about mass assignment.

Hope it helps.

Update

I see that update method cannot be called statically by the model, hence a little hack is to say:

Car::where('id', '!=', null)->update(['created_by' => 10, 'updated_by' => 15]);

PS: Beware that your created_by or updated_by field must not be unique, else it will throw some Integrity constraint violation error as a result of the query. Of course, no one mass update a unique field.

Upvotes: 6

Related Questions