user796443
user796443

Reputation:

laravel 5 insert relationship between two tables

User hasmany profiles Profile belongs to user.

Following works:

    $u = User::firstOrNew(['email' => $s['email']]);
    $u->name   = $s['name'];
    $u->avatar = $s['avatar'];
    $u->save();

    $p = new UserProfile;
    $p->provider     = $s['provider'];
    $p->provider_uid = $s['provider_uid'];

    if ($u->profiles()->save($p)) {

    }

But I don't really like it, is there a better more streamlined way? Why can't I save in 1 atomic insert?

Upvotes: 1

Views: 824

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

You are trying to save data to 2 different table, that's why you can't do this using a single insert.

The way you do it - first save the parent object, then associate the child object and save that - is how it is usually done.

You could also have a look at the push() method of Eloquent's models, that works in a similar fashion as save() but also calls save() on related models. Using this method allows to replace this code:

$a = new A;
$a->save();

$b = new B;
$b->a()->associate($a);
$b->save();

with

$a = new A;

$b = new B;
$b->a()->associate($a);

$a->push();

Upvotes: 2

Related Questions