user2773530 user2773530 - 4 months ago 15x
PHP Question

Why calling a method on User::first() works, but User::where(...) does not?

Works and returns true in php artisan tinker:

>>> User::first()->is('admin');
=> true

Returns error:

>>> User::where('id', 1)->is('admin');
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder\::is()'

Why so?


Because when using ->where() you are building a collection, but ->first(), returns the model.

For eloquent to return the model, you need to ask it to execute the query, by adding a ->get()

This however also returns a collection. You can solve this by using ->first()

User::where('id', 1)->first()->is('admin');

Edit for comments:

Try to do this, but the code above should work.

$user = User::where('id', 1)->first();
$isAdmin = $user->is('admin');