Undefined property, even though it's there
سؤال
I have an object, Brand
, and I want to print the id
of this object.
I am getting the following error when doing return Sentry::getUser()->brand()->get()->id
:
Undefined property: Illuminate\Database\Eloquent\Collection::$id
However, if I remove the ->id
part, I am getting the whole object just fine, including the id
(return Sentry::getUser()->brand()->get()
)
What am I doing wrong?
المحلول
You need to use:
return Sentry::getUser()->brand()->first()->id;
Otherwise, you end up with a collection of users (even though that collection may only contain one user).
نصائح أخرى
it might be reserved in a framework you used. My guess s that every object of any kind is a default object-type object that has an id of its own. If possible change the "id" to brand_id or something like that.
If there is only one object and will always be one, you can use return Sentry::getUser()->brand()->first()->id. That retrieves a single object, while get () returns an array of objects even if there is only one match.