Как я могу вернуть модель с его отношением / опорой в методе после firstOrNew?
Модель:
класс Клиент расширяет модель { protected $ table = 'клиенты';
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();
}
}
Метод:
$customer = Customer::firstOrNew(['unique_value' => $unique_code]);
Сделайте немного логики ... а также
return $customer;
Как вернуть $customer с locations() ?? Я тоже сделаю firstOrNew для локаций.






Используйте protected $appends = ['locations']; в своей модели.
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();
}
Или вы используете return $cusotmer->load(['locations'])
если вы хотите, чтобы он был постоянно, добавьте эту строку к вашей модели
Customer:protected $with = ['locations'];, если вы хотите получать его на лету, просто сделайте это:$customer->load('locations')или$customer->with('locations);