Sylar
Sylar

Reputation: 12092

How to include an association with a user

I need to return a json object to my view. I see my subscriptions in tinker:

\App\User::find(1)->with('subscriptions')->where('id', 1)->get();

In my view, I get my user data but the subscriptions array is emply (length: 0)

Issue one, why I could not just \App\User::find(1)->with('subscriptions')->get() This returns all users in my database.

How can I return, as json, the current user with subscriptions? The long way is to make two api calls.

Im using Cashier for the subscriptions

Upvotes: 1

Views: 42

Answers (2)

Prashant Barve
Prashant Barve

Reputation: 4325

Try to check the query log by running

    \DB::enableQueryLog();
    $data = \App\User::with('subscriptions')->find(1);
    $query = \DB::getQueryLog();
    dd($query);

It will show you what queries running behind the seens.

then for the json format try to decode into json and then pass to view.

    $json_format = json_encode($data);
    return view('user.index')->withJsonFormat($json_format);

Don't know why you want to pass the data with json format. but if you want to pass this into javascript, jquery or angular please create saperate API and call with AJAX.

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

The correct query is:

App\User::with('subscriptions')->find(1)

It will return User object with this user's subscriptions.

Upvotes: 0

Related Questions