How to make a join with the user model that brings laravel by default and a model related to it?

1

In the migration create a table called employees, and this has the fk of the users table that has the default laravel for the logeo.

Therefore the table users and employees are related, now what I intend is to obtain the employee data from the LoginController controller, this driver is already provided by laravel. Here you create a method for authentication that is as follows:

  public function login(){
    $credenciales = $this->validate(request(),[
      'email'=>'required|string',
      'password'=>'required|string'
    ]);

    if(Auth::attempt($credenciales)) {
      $user = Auth::user();          
      if($user->rol == 'admin'){
        return redirect()->route('/gestion-administrador');
      }else if($user->rol == 'supervisor'){
        return redirect('/listado-de-productos');
      }
    }
    return back()->withErrors(['email'=>'correo no valido','password'=>'contraseña incorrecta']);
  }

Now I want to show the name of the employee who logged in the view, therefore the data of the employee are in the table employees. I agree that if I want to show the data of the user table I would only do this:

<h4>Bienvenido . {{ auth()->user()->name }} </h4>

My question is how to visualize the employee's data? since user and employees are related.

Bearing in mind that in my migration in the table employees I have this:

Schema::create('empleados', function (Blueprint $table) {
            $table->increments('idEmpleado');
            $table->string('nombre',50);
            $table->string('apPaterno',50);
            $table->string('apMaterno',50);
            $table->string('puesto',50);
            $table->integer('departamento_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->foreign('departamento_id')
             ->references('idDepartamento')->on('departamentos');
            $table->foreign('user_id')->references('id')->on('users');
        });

Table user I have this:

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->string('password');
            $table->string('rol');
        });
    
asked by Luis Hernandez 05.12.2018 в 11:26
source

1 answer

0

First you must create the Employee in App model, you can use the command

php artisan make: model Employee

Create the relationship in the User model in the following way

class User extends Model
{
    /**
     * Get the empleado record associated with the user.
     */
    public function empleado()
    {
        return $this->hasOne('App\Empleado');
    }
}

Now you can call the employee's data in the following way

$empleado = User::find(1)->empleado->nombre;

Assuming that what you are trying to do is a One To One relationship, I recommend you see the Laravel documentation here link

    
answered by 05.12.2018 в 16:52