Laravel 5.4 saving pivot table -


i'm trying save pivot table error keep occurring.

sqlstate[42s22]: column not found: 1054 unknown column 'role_role_id' in 'field list' (sql: insert role_user (role_role_id, user_id) values (1, 1))

i dont know why role_role_id in double state

here models

role

public function users() {     return $this->belongstomany(user::class); } 

user

public function roles() {     return $this->belongstomany(role::class); } 

controller

   $user = new user([           'name'            => $request->get('username'),           'email'           => $request->get('email'),           'password'        => $request->get('password'),           'role_id'         => $request->get('role_id'),                  ]);          $user->save();          $role = role::find(1);         $role->users()->save($role); 

migration

  schema::create('users', function (blueprint $table) {         $table->increments('id');         $table->string('name');         $table->string('email')->unique();         $table->string('password');         $table->string('role_id');         $table->remembertoken();         $table->timestamps();     });    schema::create('roles', function (blueprint $table) {             $table->increments('role_id');             $table->string('role');             //required             $table->string('created_by');             $table->string('updated_by');             $table->string('is_active');             $table->timestamps();         });          schema::create('role_user', function (blueprint $table) {             $table->integer('role_id');             $table->integer('user_id');             $table->primary(['role_id', 'user_id']);         }); 

p.s. followed eloquent documentation of laravel https://laravel.com/docs/5.4/eloquent-relationships#the-save-method

for many-to-many should use attach() method:

$user = user::create($request->all()); $user->roles()->attach(1); 

also, change this:

$table->increments('role_id'); 

to:

$table->increments('id'); 

and remove line:

$table->primary(['role_id', 'user_id']); 

then recreate tables . primary not work pivot table foreign keys.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -