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;
source share