Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the difference of find and get in Eloquent

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 ?

like image 364
huangwei jie Avatar asked Dec 22 '14 07:12

huangwei jie


2 Answers

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.

Uses

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

Equivalent with 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;
like image 54
lukasgeiter Avatar answered Oct 26 '22 10:10

lukasgeiter


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

like image 21
Jarek Tkaczyk Avatar answered Oct 26 '22 11:10

Jarek Tkaczyk