SexyMF
SexyMF

Reputation: 11155

Laravel serialize object to array with foreign keys

class Customer extends Model
{
    public function country(){
        return $this->belongsTo(Country::class,'country_id');
    }
}

$customer = Customer::Find(1);

when doing $customer->toArray() it will serialize 'country_id' and not the entire country object.

Is it possible that country object will be serialized as well?

Thanks

Upvotes: 0

Views: 830

Answers (1)

Shobi
Shobi

Reputation: 11451

You need to load country relation ship explicitly,

$customer = Customer::findOrFail(1)->load('country');

$customer->toArray()

another way of doing is this by using with

$customers = Customer::with('country')->find(1)->toArray(); 

If you want to load one or more relationship always, then you can specify them in the protected $with property in the model, so the relationships are always eager loaded,

eg:

  protected $with = ['country'];

Upvotes: 1

Related Questions