Jack Franzen
Jack Franzen

Reputation: 778

Laravel 5 Eloquent, double one-to-one save (get Id before save)

$profile = new Profile;
$user = new User;

$user['profile_id'] = $profile['id'];
$profile['user_id'] = $user['id'];

$profile->save();
$user->save();

So I have the relationships setup using "hasOne" in both Models files. These are NOT NULL FOREIGN KEYS so I need to define the id relationship immediately. But ['id'] is not available until after save. How can I do these 2 save operations at the same time?

Upvotes: 1

Views: 977

Answers (1)

Pawel Bieszczad
Pawel Bieszczad

Reputation: 13325

You should have the foreign key in only one of the tables, and define the other relationship as belongsTo

EDIT

If you keep the user_id in the profiles table, then add this to your user model

public function profile()
{
    return $this->hasOne('App\Profile');
}

then you can do this

$user = new User;
$user->save();
$user->profile()->save(new Profile());

Upvotes: 1

Related Questions