Emmanuel Scarabin Emmanuel Scarabin - 4 months ago 12
JSON Question

How to include an Eloquent relationship into JSON conversion result?

I want to return JSON data to my Angular front-end with Laravel 5 but I am stuck with this problem : I have an Alert eloquent model which has a relationship with AlertFrequency model:

class Alert extends Model
{
public function alertFrequency()
{
return $this->belongsTo('App\Models\AlertFrequency');
}
}


but when I try to return the alerts listing as a JSON...

$alerts = Auth::user()->alerts->toJson();

return $alerts;


here is what I get :

[{"id":9,"title":"fqdsgsq","place":"gdqsgq","user_id":1,"alert_frequency_id":3,"job_naming_id":3,"created_at":"2016-07-16 14:09:41","updated_at":"2016-07-16 14:09:41"}]


So I do have the "alert_frequency_id" column value but not the actual AlertFrequency object

The only workaround I found to be working so far is this :

$alerts = Auth::user()->alerts;

foreach ($alerts as $alert) {
$alert->jobNaming = $alert->jobNaming;
$alert->alertFrequency = $alert->alertFrequency;
}

return $alerts;


which is pretty ugly...

Answer

You need to manually load the relationship. This is called lazy eager loading a relationship.

$alerts = Auth::user()->alerts->load('alertFrequency')->toJson();
return $alerts;

When you do Auth::user()->alerts->toJson() you just fetched the data from the Alert model, but you want data from another model (another table) then you need to tell that using the load method.

Bonus

If your code is in a controller method or a router closure instead of calling toJson() you can just return the collection and Laravel will do that for you. Example:

public function controllerMethod() {
    return Auth::user()->alerts->load('alertFrequency');
}

Happy coding!