0
votes

How can I return the model with his relation / pivot in a method after a firstOrNew?

Model:

class Customer extends Model { protected $table = 'customers';

protected $primaryKey = 'customer_id';

public $timestamps = true;


protected $fillable = [
    'email',
    'first_name',
    'last_name',
    'address',
    'city',
    'county',
    'country',
    'phone',
    'organization_id',
    'unique_value'
  ];

protected $guarded = [];

public function locations()
{
    return $this->belongsToMany('App\Models\CustomerLocations', 'customer_customer_locations', 'customer_id', 'address_id')->withTimestamps();
}

}

Method:

$customer = Customer::firstOrNew(['unique_value' => $unique_code]);

Do some logic... and

return $customer;

How can I return the $customer with locations()?? I will do a firstOrNew for locations too.

1
if you want to have it all the time then add this line to your Customer model: protected $with = ['locations'];, if you want to have it on the fly then simply do this: $customer->load('locations') or $customer->with('locations);Mohamed Kawsara

1 Answers

1
votes

Use protected $appends = ['locations']; in your Model.

protected $primaryKey = 'customer_id';

public $timestamps = true;

protected $appends = ['locations'];



protected $fillable = [
    'email',
    'first_name',
    'last_name',
    'address',
    'city',
    'county',
    'country',
    'phone',
    'organization_id',
    'unique_value'
  ];

protected $guarded = [];

public function locations()
{
    return $this->belongsToMany('App\Models\CustomerLocations', 'customer_customer_locations', 'customer_id', 'address_id')->withTimestamps();
}

Or you use return $cusotmer->load(['locations'])