Mintendo
Mintendo

Reputation: 567

Laravel return model relationships in JSON

When I try to return model relationships in JSON, I don't see the relationship fields. That's my query:

$customer_subscriptions = CustomerSubscription::has("customer")
                ->has("subscription")
                ->has("federationDiscipline")
                ->where("customer_id", "=", $customer_id)
                ->whereHas("subscription", function($query) use($company_id) {
                    $query->where("company_id", "=", $company_id);
                })
                ->orderBy("start_date", "asc");

        return $customer_subscriptions;

That's my result:

[0]=>
  array(14) {
    ["id"]=>
    int(2)
    ["customer_id"]=>
    int(1)
    ["subscription_id"]=>
    int(1)
    ["federation_discipline_id"]=>
    int(1)
    ["start_date"]=>
    string(10) "2017-04-01"
    ["end_date"]=>
    string(10) "2017-05-31"
    ["external_id"]=>
    NULL
    ["notes"]=>
    NULL
    ["created_user_id"]=>
    int(1)
    ["updated_user_id"]=>
    NULL
    ["deleted_user_id"]=>
    NULL
    ["created_at"]=>
    string(19) "2017-06-05 07:28:00"
    ["updated_at"]=>
    string(19) "2017-06-05 07:28:00"
    ["deleted_at"]=>
    NULL
  }

I don't see the subscription's and the customer's relationship field. The result of query should return JSON to AJAX

Upvotes: 3

Views: 9663

Answers (3)

Jerodev
Jerodev

Reputation: 33186

You have to eager load the relationships for them to be included in the json output. You current query only looks if there are relations, it doesn't load them.

For example:

$customer_subscriptions = CustomerSubscription::has("customer")
    ->has("subscription")
    ->has("federationDiscipline")
    ->where("customer_id", "=", $customer_id)
    ->whereHas("subscription", function($query) use($company_id) {
        $query->where("company_id", "=", $company_id);
    })
    ->orderBy("start_date", "asc")
    ->with('customer');  // <--- Eager loading the customer

return $customer_subscriptions;

    return $customer_subscriptions;

Upvotes: 5

user320487
user320487

Reputation:

Use the with() method to include relationships in results. For example:

$customer_subscriptions = CustomerSubscription::with("customer")->...

Alternatively, use the protected $appends = [...] attribute on models to force the relationship to be loaded for every query. Keep in mind, however, this will impact queries everywhere the model is used, as it forces the database to query for those relationships every time.

Upvotes: 3

Brian Glaz
Brian Glaz

Reputation: 15676

Using ->has only acts as a where condition, it doesn't load that relation in to your result set.

You want to use ->with instead.

In your case ->with('subscription','federationDiscipline')

https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

Upvotes: 6

Related Questions