Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
Maxcot Avatar asked Jan 06 '23 13:01

Maxcot


1 Answers

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

like image 186
Serak Shiferaw Avatar answered Jan 16 '23 22:01

Serak Shiferaw