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.
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