How to save data in a table related to another in Laravel?

0

I have a model called User that can take on several roles, such as an Administrator, a Supervisor, a teacher, anyway. Therefore for each of the roles I create other entities that will be related to the User model. Now, create a form to be able to save an Administrator, but this is where the doubt comes to me

How can I save an Administrator with the basic user data and insert it in User and relate it to the user? I leave the code of the migrations of each of the entities.

User / User Entity

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->enum('id_type',['Cedula','Cedula extrangera','Tarjeta de identidad']);
            $table->string('id_number')->unique();
            $table->string('password');

            //Optional
            $table-enum('net',['Pre-Juvenil','Juvenil','Universitaria','Ejecutiva','Matrimonios menores','Matrimonio mayores'])->nullable();
            $table-enum('ministerial_state',['Lider','Estudiante ADO','Graduado no lanzado'])->nullable();
            $table->string('email')->unique()->nullable();
            $table->string('telephone')->nullable();
            $table->string('cellphone')->nullable();
            $table->date('birthday')->nullable();
            $table->string('address')->nullable();
        });
    }

Administrator Entity / Administrator

public function up()
    {
        Schema::create('administrators', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
    
asked by Juan Carlos Peña M. 21.12.2016 в 04:14
source

1 answer

1

That's how I do it

function almacenar(Request $request) {
    $data=$request->all();//obtengo las variables
    $this->modelUsuario->setVariables($data);//Asigno las variables necesarias
    $bool=$this->modelUsuario->save();//return true o false
    if($bool){
      $idUsuario=$this->modelUsuario->id; //considerando que id es primary key del modelo
      $this->modelAdministrador->setIdAdministrador($idUsuario);//Asigno la variable Idusuario 
      $this->modelAdministrador->setVariables($data);//Asigno las variables necesarias
      $boolAdministrador= $this->modelAdministrador->save();
    }
  return  $boolAdministrador;
}

I hope it serves you: D

    
answered by 21.12.2016 в 16:08