0

I have 2 classes in Laravel

class Company
{
  public function people()
  {
     return $this->hasMany('Person');
  }
}

class Person 
{
  public function company()
  {
    return $this->belongsTo('Company');
  }
}

Now in another class, I am creating a person object and setting company_id with a defined variable $companyId.

$person = new Person;
$person->company_id = $companyId; //Code not executing after it.
$person->save();

When I am setting $companyId in $person, it is just being in recursive call and never come back.

I have also tried this code as well, but no luck, again, it is stuck somewhere and never save.

$company = Company::find($companyId);
$person = new Person;
$company->people()->save($person); // Never execute this

Please provide some sight, what wrong I am doing, I googled for this but not found which resolve this.

  • EDIT *

This app was created and maintain in laravel 4.2 and there it is working fine, but while upgrading this to laravel 5.7, this is giving issue here.

Thanks

Yograj Gupta
  • 9,811
  • 3
  • 29
  • 48

1 Answers1

1

can you try below code may be it will work for you.

Please add a relationship like this in your code.

class Company
{
  public function people()
  {
     return $this->hasMany('App\Person');
  }
}

class Person 
{
  public function company()
  {
    return $this->belongsTo('App\Company');
  }
}

And try to save Person object like this here I don't know fields of person table so for a demo, I have used a name, so replace it as per your requirements.

$comment = new App\Person(['name' => 'test']);

$company= App\Company::find(1);

$company->people()->save($person);
Jigar
  • 3,055
  • 1
  • 32
  • 51
  • I am trying your suggestion, but facing other issues, so once I will resolve that, I will let you know. – Yograj Gupta Mar 25 '19 at 05:58
  • Thanks Joy, As per your suggestion, I am able to save data without issue, but I found that issue some how is with our architecture, as there are many multi level hierarchy inheritance, and many overloads as well of setting attributes. So by xDebug, I got those issues. Thank you again, at-least I got help from your answer. – Yograj Gupta Mar 25 '19 at 13:21