15

In Laravel, i´m trying to show relation elements between Auth::user (Users) and Departments. In User table i have id, name, and department_id. In Departments table I have id and name.

In user model i create

public function department()
    {
        return $this->belongsTo('App\Models\Department');
    }

Then, in blade template I try

Auth::user()->department

But return null and doesn´t show linked departments. Null is incorrect, all users have departments. Soo, ¿Any help? ¿What´s wrong in relation?

4 Answers 4

31

You can try this User::with('departmento')->find(Auth::id());

Sign up to request clarification or add additional context in comments.

3 Comments

Can i use User::with('departament')->find(Auth::id()); in boot to share variable in all templates?
In your "Controller/BaseController" add folowwing code: public function __construct() { $user = User::with('departament')->find(Auth::id()); View::share('user', $user); } Btw, It's not a good idea.
There is no point is querying the database since the Auth have already done that! The missing point is that the author had a foreign key not complaint to Laravel's Eloquent way of relating tables. In this case "singulartablename_id".
19

This method uses less queries - the others go after the user table twice:


auth()->user()->load(['department']);

1 Comment

It's not working i am getting error.. Class "App\Models\ResellerUserDetailModel" not found. form where you load "load method" ?
5

You should add 'department_id' as a second parameter ($foreignKey) when calling belongsTo method, because it will searching for departmento_id by default.

public function departamento()
{
    return $this->belongsTo('App\Models\Departamento', 'department_id');
}

Or just rename User::departamento() method to User::department()

public function department()
{
    return $this->belongsTo('App\Models\Departamento');
}

1 Comment

In fact, you must pass the foreign id since the table is not compliant to Laravel's Eloquent way of relating tables. In this case, if the foreign id is not "singulartablename_id" it won't work.
3

Relation works with Model. Auth uses the session it not uses relation

Use User Model instead

  optional(User::find(Auth::id())->departmento)->department_name

4 Comments

I use a global variable 'user' with Auth::user() to avoid to repeat code and can show/use actual user in all templates. So your answer is correct but i need it to send Auth::id in all templates...
As you already using Auth::user()->departmento you just need to replace with above code
{{optional(User::find(Auth::id())->departamento)->name}} Return null
Use \Auth instead

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.