Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent - checking if returned object is valid or not

I'm retrieving objects using Laravel's Eloquent, and I'm trying to see if the object is valid or not.

For instance

$user = User->where('first_name', 'Adam')->first(); // what if there are no Adams?

I get a Builder object when there are no Adams and a User object when there is. Without using instanceof, is there a way to find out if the object returned is a valid User? Ideally, Eloquent would have just returned a null or some InvalidObject object as a response.

like image 334
StackOverflowed Avatar asked Jan 10 '23 00:01

StackOverflowed


1 Answers

first method return null if a model is not found, you may also use firstOrFail method to throw an exception

like image 175
Razor Avatar answered Jan 28 '23 23:01

Razor