3

I am trying to get my users role relation through the Auth::user() function. I have done this before but for some reason it is not working.

Auth::user()->role

This returns the error trying to get property from non-object.

In my user model I have this:

public function role()
{
    return $this->belongsTo('vendor\package\Models\Role');
}

In my role model I have:

public function user()
    {
        return $this->hasMany('vendor\package\Models\User');
    }

When I do this it returns the name of my role, so my relations are correct I think:

User::whereEmail('[email protected]')->first()->role->name

What am I missing?

2
  • are you sure that Auth::user() returns an Eloquent Model? Commented Mar 11, 2015 at 15:43
  • Yes Auth::user() returns eloquent instance of User model (when found). Commented Mar 11, 2015 at 15:49

2 Answers 2

4

Auth::user can return a non-object when no user is logged in. You can use Auth::check() to guard against this, or even Auth::user itself:

if(!($user = Auth::user())) {
    // No user logged in
} else {
    $role = $user->role;
}

Alternatively:

if(Auth::check()) {
    $role = Auth::user()->role;
}
Sign up to request clarification or add additional context in comments.

7 Comments

or simply rely on middleware! and not checking needed. There is one that L5 is shipping out with. app/Http/middleware/Authenticate.php and registered as "auth" in app/Http/kernel.php.
That's correct, and a great point. OP didn't specify what version of Laravel he's on, though, so I assumed Laravel 4.
I assumed L5 :) but either way if L4 there are filters for that.
For all we know this code is running inside of a filter, OP makes no distinction in his question.
Sorry that I was not clear enough, the version of Laravel that I am using for this project is 4.2 and the code that I'm trying to run is located in a filter 'role' This filter is executed after the auth filter so my user is definitely logged in to my application. Auth::user() returns my user by the way.
|
-1

Ok I found out why it wasn't working for me. The thing is that my User model where I was talking about was a part of my package, and because Laravel has it's own User model in the default Laravel installation it was not working.

Your package model does not override an already existing model. I solved my problem by making a Trait instead of a model for my package.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.