I have two models: User
and Roles
. I need to insert User
and his Roles
from same form.
$user = new User;
$user ->name = $request ->input('name');
$user ->email = $request ->input ('email');
$user -> password = $request ->input ('pass');
$user ->save();
$role = new Role;
$role ->name = $request ->input('role');
$role ->explain = $request ->input('exp');
$role ->save();
$role ->roles() ->save($user);
It gives me an error.
User
model:
public function roles()
{
# code...
return $this ->hasMany('App\Role');
}
Role
model:
public function users()
{
# code...
return $this ->belongsTo('App\User');
}
migrations:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->text('name');
$table->string('explain');
$table->timestamps();
//cascade
$table->foreign('user_id')->references('id')->on('users')- >onDelete('cascade');
});
I think that is the relationship is done correctly.
many
.roles
, CONSTRAINTroles_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
(id
) ON DELETE CASCADE) (SQL: insert intoroles
(name
,explain
,updated_at
,created_at
) values (sss, asw, 2016-02-21 07:34:02, 2016-02-21 07:34:02))