I created 3 tables : users , roles and role_user.
The user model :
public function roles()
{
return $this->belongsToMany('Role');
}
The following is OK, I'm able to get the relation :
$roles = User::find(1)->roles;
But when I do this instead :
$roles = User::where('name', 'Test')->get()->roles;
I get this error :
Undefined property: Illuminate\Database\Eloquent\Collection::$roles
What am I doing wrong?
What is the difference between find
and where
?
If I want to use where
to fetch a relation, how can I do it ?
get()
get()
simply executes whatever (select) query you have built. It will return a collection (Illuminate\Database\Eloquent\Collection
) in any case. That's the reason for your error message. You want the $roles
of one model but you are trying to get it from a collection, which is obviously not possible.
find()
find()
is used to fetch one or many models by its / their primary key(s). The return value will either be a single model, a collection or null
if the record is not found.
$user = User::find(1); // returns model or null
$users = User::find(array(1, 2, 3)); // returns collection
first()
first()
returns the first record, so you get a single model even if the result may would contain multiple records
$user = User::where('id', 1)->first();
returns the same as
$user = User::find(1);
Meaning for your case you want to use first()
instead of get()
$roles = User::where('name', 'Test')->first()->roles;
get
returns a collection, find
returns single model. So obviously you can't call ->name
on the collection of users.
User::find(1); // single User model
User::find([1,2,3]); // collection of User models
User::get(); // collection of User models
There are also other methods returning the query result, eg.:
User::first(); // single User model
User::pluck('name'); // single value of name field of the first row
and so on.. read the docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With