bank insert with relationship N: M [duplicate]

2

I need to insert users into my database the MySQL data already with the N:M relationship, but I do not know how to do that.

Migrate:

Schema::create('usuarios', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nome');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

 Schema::create('rotas', function (Blueprint $table) {
        $table->increments('id');
        $table->string('action');
        $table->timestamps();
    });

 Schema::create('usuarios_rotas', function (Blueprint $table) {
        $table->integer('usuario_id')->unsigned();
        $table->foreign('usuario_id')->references('id')->on('usuarios');
        $table->integer('rota_id')->unsigned();
        $table->foreign('rota_id')->references('id')->on('rotas');
    });

Model:

class Usuario extends Model
{


 protected $fillable = [
        'nome', 'email','password'
    ];

public function rotas() {

    return $this->belongsToMany(Rota::class);
}
}

class Rota extends Model
{

protected $fillable = [
    'rota'
];

public function usuarios() {

    return $this->belongsToMany(Usuario::class);
  }
}
    
asked by anonymous 08.02.2018 / 15:44

1 answer

2

In Laravelle, it's quite simple to do that. If you know the route ID and route ID, just use the attach method to do this:

Example:

 Usuario::find($usuario_id)->rotas()->attach($rota_id);
    
08.02.2018 / 16:14