CoffeeAddiKt
CoffeeAddiKt

Reputation: 109

Can't set new value to Model's property

I am trying to set new value to Model's property but it's not working. I am using dd() right after I set the new value but it keeps the old value.

$business->users()
    ->where('userable_id', $business->id)
    ->where('userable_type', 'App\Models\Business')
    ->first()->first_name = "New";

Upvotes: 1

Views: 3069

Answers (3)

Tarasovych
Tarasovych

Reputation: 2398

Try this instead:

$business->users()
    ->where('userable_id', $business->id)
    ->where('userable_type', 'App\Models\Business')
    ->first()->update(['first_name' => "New"]);

Direct object property assign like $model->attribute = 'foo'; affects only in-memory state and doesn't make changes in the database.

So you want to go either

$model->update(['attribute' => 'value']);

or

$model->attribute = 'value';
$model->save();

Reference


Update 1:

as I've written in the comments to my answer, first() might return null sometimes if no one model was found. I'd like to advice firstOrFail() instead.

Note, that there is no predefined handler for ModelNotFound exeption (thrown by firstOrFail()), so you'd like to handle such error manually in Handler class, otherwise you'll get default 404 Laravel page.

Upvotes: 8

Leonardo Rossi
Leonardo Rossi

Reputation: 3022

To access a method/field right after the ->first() method is a very bad practice.

If no model is found, PHP will raise an error because you are trying to access method/property on a null value.

Use instead

$user = $business->users()
    ->where('userable_id', $business->id)
    ->where('userable_type', 'App\Models\Business')
    ->first();
$user->first_name = 'New';
$user->save();

// or, if 'first_name' is in your model $fillable array
$user->update(['first_name' => 'new' ]);

Upvotes: 1

Bruce
Bruce

Reputation: 96

$business->users()
    ->where('userable_id', $business->id)
    ->where('userable_type', 'App\Models\Business')
    ->first()->update(['first_name' => 'New']);

Upvotes: 3

Related Questions