laravel one to many inserting laravel one to many inserting php php

laravel one to many inserting


Your issue is that you saved your Role before you associated it with a user. Since you didn't associate it to a user, your roles.user_id field is empty, and that violates your foreign key.

You need to change your code to associate the user before saving the role, as shown below:

// create the user$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');// option 1:// this will set the user_id on the role, and then save the role to the db$user->roles()->save($role);// option 2:// associate the user to the role (sets the user_id field)// then you need to save your role$role->users()->associate($user);$role->save();

Use option 1 or option 2, not both.

Edit

Additionally, when not passed in, the belongsTo relationship builds the foreign key based on the name of the relationship function. Since your method is named users, it is going to look for the users_id field, which is not correct. You will either need to pass in the correct foreign key name as the second parameter, or rename your relationship method from users() to user().

// option 1// pass in the foreign key field as the second parameterpublic function users(){    return $this->belongsTo('App\User', 'user_id');}// option 2// rename the relationship to userpublic function user(){    return $this->belongsTo('App\User');}

You can do both, but at the least, it would make the code more logical if you were to rename the method to user().


this error because you didn't pass the user_id for the roles tables. it is a foreign key in this table and must be passed.you can save your one to many relation tables in this way:

https://laravel.com/docs/4.2/eloquent#inserting-related-models

firstly you save the master table user row, then by find() method you can save all details rows in roles table like the link example.

$role = new Role(array('','','','')); // array of roles row values you want save$user = User::find(1); // where 1 is id$role = $user->roles()->save($role );