Ash Ash - 7 months ago 17
PHP Question

How do I insert multiple joined models in Laravel 5

I'm trying insert a sample user into my database.

My database contains 3 models, these should all be populated at the same time. The models are: Users, Profiles and Teams.


  • Each User has one Profile (one to one relationship).

  • Each User can
    be part of many Teams and each Team can have many Users (many to many
    relationship).



My models are setup correctly with the relevant
belongsTo()
/
hasMany()
references etc.

In laravel, my code looks like this:

$user = new User([ 'email' => 'sample@sample.com', 'password' => bcrypt('password1'), 'username'=> 'sampleuser']);
$profile = new Profile(['name' => 'Sample','bio' => 'All about me']);
$team = new Team(['name' => 'SuperAdmins']);

$user->profile()->save($profile);
$user->teams()->attach($team, ['type' => 4]);


How can I get this to work>? this does not work, with my console citing
'user_id' cannot be null
when inserting into the profile table.

EDIT:
Thanks, to the answer from Ross Wilson, I went with:

$user = new User([ 'email' => 'sample@sample.com', 'password' => bcrypt('password1'), 'username'=> 'sampleuser']);
$user->save();

$profile = new Profile(['name' => 'Sample','bio' => 'All about me']);
$user->profile()->save($profile);

$team = new Team(['name' => 'SuperAdmins']);
$user->teams()->save($team, ['type' => 4]);

Answer

With your example you never actually persist the User model.

Add $user->save(); before saving profile relationship.

You'll also need to persist the $team before attaching it to the User

Hope this helps!