The difference is to find and get into the "Eloquent"

I created 3 tables: users, roles and role_user.

user model:

public function roles() { return $this->belongsToMany('Role'); } 

it's ok i can get the attitude

 $roles = User::find(1)->roles; 

But when I changed

 $roles = User::where('name', 'Test')->get()->roles; 

Undefined property: Illuminate\Database\Eloquent\Collection::$roles

So is it wrong or is "find" where is the difference? if I want to use, where for the sampling relation, how can I do this?

+5
source share
2 answers

get()

get() simply executes any (selected) request that you created. It will return the collection ( Illuminate\Database\Eloquent\Collection ) anyway. This is the reason for your error message. You want the $roles one model, but you are trying to get it from the collection, which is obviously not possible.

find()

find() used to retrieve one or more models by his / their primary key . The return value will be either a separate model, or a collection, or null if the record is not found.

Using

 $user = User::find(1); // returns model or null $users = User::find(array(1, 2, 3)); // returns collection 

Equivalent to first()

first() returns the first record, so you get one model, even if the result can contain several records

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

returns the same as

 $user = User::find(1); 

The value for your case you want to use first() instead of get()

 $roles = User::where('name', 'Test')->first()->roles; 
+13
source

get returns a collection, find returns a single model. Therefore, obviously, you cannot call ->name in the user collection.

 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 that return a query result, for example:

 User::first(); // single User model User::pluck('name'); // single value of name field of the first row 

etc. read documents

0
source

Source: https://habr.com/ru/post/1209685/


All Articles