get()
get()
simply executes whatever (select) query you have built. It will return a collection (IlluminateDatabaseEloquentCollection
) 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;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…