Maxcot
Maxcot

Reputation: 1617

Laravel 'save()' for 'hasmany' Model

If I have a two models, with a hasMany relationship, so my Car hasmany CarOwners, I would like to use to use the firstOrCreate method to create a new car.

If I'm creating a new car then I need to create the first CarOwnertoo.

Without leveraging any laravel functionality, I would

  1. create a new car,
  2. get the ID of the new car object
  3. create a new CarOwner, associating it with the recently created car

Isn't there a way to do this in one go? I can do the queries to find the CarOwners of the chosen car, but I can't see how to save across multiple tables.

Upvotes: 5

Views: 34209

Answers (1)

Serak Shiferaw
Serak Shiferaw

Reputation: 167

Refer to laravel manual .if you already created a Model for them it would be like this

car->carOwners()->save($owners)

link https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models

Upvotes: 11

Related Questions