Laravel Eloquent “findOr” Method

Reza Khademi
2 min readApr 30, 2022

--

We have some useful methods when we want to find our desired data from a table.

e.g:

Larave Eloquent find method

Well as you saw above, we can use find() method but the good thing about findOrFail() method is if eloquent can’t find data that we are looking for, it will automatically return a 404 with a Illuminate\Database\Eloquent\ModelNotFoundException exception which will be much easier and better to handle.

But imagine we want to have another term or need to do something else after finding the desired record, well eloquent give you findOr() method where you can define whatever you want in callback function!

e.g:

We can do some much things in callback and to be honest it’s quite useful at some situations.

Even we can take a step further and do much more like below:

Laravel Eloquent findOr method

We can use this structure for firstOr() method but mind where() function before the firstOr() method:

Laravel Eloquent FirstOr method

That’s it.

--

--