3
votes

I am struggling to use laravel push() function

My Code is here:

$company = new Company(array('name' => 'Company 1'));
$company->persons[] = new Person(array('name' => 'Company 1 Person 1', 'mobile' => 12345));
$company->persons[] = new Person(array('name' => 'Company 1 Person 2', 'mobile' => 112233));
$company->push();

When it gets stored: Company gets stored well, but for company persons, it stores company_id to 0

Larave Documentations says:

Sometimes you may wish to save not only a model, but also all of its relationships. To do so, you may use the push method:

$user->push();

what is wrong?

1
I've never used push() before but it seems like maybe you aren't using it correctly. The docs don't give much mention to it. See this questionJared Eitnier
I have a feeling that push will only work with pre-defined relationships, not creating new records.Jono20201

1 Answers

4
votes

It's not Doctrine ;)

push could do it, BUT it wouldn't be nice and easy (below you can find out how)

And here's what you can do instead (nice and easy way):

// still you need already existing Company, so save it first
$company = new Company(array('name' => 'Company 1'));
$company->save();

$company->persons()->createMany(array(
  array('name' => 'Company 1 Person 1', 'mobile' => 12345),
  array('name' => 'Company 1 Person 2', 'mobile' => 12345)
));

This will save new Person models and associate them with the Company


push would do the job, but only if you do it with already existing parent AND you first associate child models:

$company = Company::first(); // or any existing

$person = new Person(array('name' => 'Company 1 Person 1', 'mobile' => 12345));
$person->company()->associate($company);

$anotherPerson = new Person(array('name' => 'Company 1 Person 2', 'mobile' => 12345));
$anotherPerson->company()->associate($company);

$company->persons[] = $person;
$company->persons[] = $anotherPerson
$company->push();

Obviously this is more work and it's definitely not the way I would suggest.