Renaldo Khowilya
Renaldo Khowilya

Reputation: 35

how to get specific item just from user id to show at view

this is my current code

    $products=Product::all();
    return view('user.products.index', compact('products'));

this code return all the product to the view.
how to return only the login user's uploaded product to the view?

Upvotes: 1

Views: 110

Answers (2)

Ankit Jain
Ankit Jain

Reputation: 1036

If you have made relationship between the user's table and the product table by using foreign key or you are saving linking user's product with his id, It can be possible to show in this way-

use Auth;
Product::where('user_id', Auth::id())->get();

OR if you are using guard then call in this way--

use Auth;
Product::where('user_id', Auth::guard('guard_name')->id())->get();

It will return the array of all the products associated with the logged in user.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You can do this by using where():

Product::where('user_id', auth()->id)->get();

Or by using relationship:

auth()->user()->products()->get();

Or you can use lazy eager loading:

auth()->user()->load('products');

Upvotes: 0

Related Questions