0

Actually, I want to fetch data using Model object not through Model facade like mention below.

$user = $this->getGuard()->user();

Above user is current logged user which is

        "id": 6,
        "name": "kuser",
        "email": "[email protected]",
        "phone": "03345154067",
        "is_subscribed": 0,
        "subscription_date": null

But when I try to fetch same $user object with its related model like cards, by execute $user->with(['cards'])->first(); than it gives first record of user table with cards like mentioned below.

        "id": 1,
        "name": "admin",
        "email": "[email protected]",
        "phone": "03056494616",
        "is_subscribed": 1,
        "subscription_date": "2019-10-08",
        "cards": []

Above mentioned record which is user object. It is first record of my user table.

Actually, I am expecting.

      "id": 6,
        "name": "kuser",
        "email": "[email protected]",
        "phone": "03345154067",
        "is_subscribed": 0,
        "subscription_date": null

with its related model cards like

      "id": 6,
        "name": "kuser",
        "email": "[email protected]",
        "phone": "03345154067",
        "is_subscribed": 0,
        "subscription_date": null
        "cards":[] // array of cards those belongs to it.

3 Answers 3

2

You can use Lazy Eager Loading, you don't have to query for the user again, you already have it:

$user = $this->getGuard()->user();

$user->load('cards');

Laravel 6 Docs - Eloquent - Relationships - Lazy Eager Loading

Sign up to request clarification or add additional context in comments.

1 Comment

yep its working fine. This is what, I really wanted yesterday. Thanks
1

Use a simple where ?

$user->where('id', Auth::id())->with(['cards'])->first();

won't that work?

4 Comments

It works, infact now, I used to fetch this way User::with(['cards'])->find($user->id). But, it has some little bit extra effort so, I try to find better one approach.
whats the "extra effort" here if i may ask?
$user->where('id', Auth::id())->with(['cards'])->first(); I think it should be like $user->with('cards') and that's it. Hope so, you got that point. But anyway it also fair enough.
You dont wanna use $user = $this->getGuard()->user();, you also dont wanna use where, script cant assume itself which user you are reffering to
0

Here is another way

User::with(['cards'])->find($user->id);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.