Can we use update() with find() in the laravel eloquent?

Viewed 407

When I use update() with find() and invalid id like

User::find(100)
     ->update(['is_valid' => true])

I got error:

Error: Call to a member function update() on null

But when I use update() with where and invalid id like

User::where('id', 100)
     ->update(['is_valid' => true])

It returns false as expected. so what is the problem when I use find()? How to solve it?

1 Answers

if you want to use

User::find(100)
     ->update(['is_valid' => true])

this without error you can use optional() helper like this

optional(User::find(100))
     ->update(['is_valid' => true])

ref link https://laravel.com/docs/8.x/helpers#method-optional


User::find(0) ---> null

it retrun model instance if data found and if not found it it null so you cannot chain ->update() on null that's why your getting error

User::where('id', 100) ----> eloquent instnace

it is a laravel Eloquent so here you can chain as many function which are avilable in eloquent

Related