Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Auth::user relationship

Tags:

laravel

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?

like image 833
El Hombre Sin Nombre Avatar asked Apr 04 '18 08:04

El Hombre Sin Nombre


People also ask

How does laravel Auth attempt work?

The attempt method accepts an array of key / value pairs as its first argument. The password value will be hashed. The other values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column.

What is Auth PHP in laravel?

Laravel includes built-in authentication and session services which are typically accessed via the Auth and Session facades. These features provide cookie-based authentication for requests that are initiated from web browsers. They provide methods that allow you to verify a user's credentials and authenticate the user.


1 Answers

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


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

like image 118
acidjazz Avatar answered Nov 16 '22 02:11

acidjazz