0

This is the scenario.

Im filling in a form and this form has Name, Email , Country and Skills (which is a dropdown with a number of skills which is populated from a database table skills prefilled). When the person is filling the form he can select multiple skills he possess. This means the user has many skills.(One to many). After the user fills the form and click submit. I want the UserTable saved and also the UserSkills also save related to the user.

The problem is dont have the user saved yet so cant fetch theid to save the skill on. Both has to be saved the same time when save is pressed.

How best can I do this in Laravel

user3602477
  • 99
  • 10
  • Possible duplicate of [Laravel, get last insert id using Eloquent](http://stackoverflow.com/questions/21084833/laravel-get-last-insert-id-using-eloquent) – snitch182 Nov 01 '16 at 14:10
  • you want to look for examples of "get last insert id" like here: http://stackoverflow.com/questions/21084833/laravel-get-last-insert-id-using-eloquent – snitch182 Nov 01 '16 at 14:11

2 Answers2

1

I assume the skill ids are formatted as an array. You have a pivot table named UserSkills. Create a belongsToMany with User class as this will be a many to many relationship (one user can have multiple skills and one skill can belong to multiple users). So in your App\User class

public function skills(){
  return $this->belongsToMany('\App\UserSkills','table_name','user_id','skill_id');
}

Detailed info on pivot table creation

After that, when you create an user

$user = new User();
$user->username = $request->input('username');
// other inputs or use a `create` method
$user->save();

after that attach the skill ids to the newly created user.

$user->skills()->attach($request->input('skill_ids'));
shoieb0101
  • 1,524
  • 10
  • 15
0

You can assign a var to the newly created user like so:

$user = User::create([
    'username' => 'user'
]);

You can then use that $user anywhere below

UserSkills::create([
    'user_id' => $user->id,
]);
Adam
  • 455
  • 1
  • 3
  • 18
  • how do I get the information of the skills injected also in the same controller method because I now only get the information of user which is injected via Request in the controllermethod – user3602477 Nov 02 '16 at 01:03