Skip to content
Advertisement

How can I display data from another table only authenticate user [closed]

I have two tables on my database named user and products. I can register by email in the user table and login. in my products table I can add some data like product name, product detail. suppose I login with test@gamil.com it takes me to add a data page when I add data I see my data in my index.blade.php page. and if i add some data again it adds some data and shows in my index.blade.php so I can see two data after login with test@gamil.com. Now I logout from test@gmil.com and register another user in user tables like test2@gmail.com and login with it after login I can see data which two I have stored in my products table by test@gmail.com. But I don’t wont to see data form products table which I entered by using test@gmai.com I want a fresh index.blade.php for user two which is test2@gimai.com and if I add some data for user two those date will show only for him not user one. This is my ProductController.php

public function index()
{
    $user = Auth::user();
    $products = $user->products;
    $products = Product::latest()->paginate(1);

    return view('products.index',compact('products'))
           ->with('i', (request()->input('page', 1) - 1) * 5);
}

This code can show the last data for authenticate user. but I want if I login with one id and enter 5 data it will show those data only for him not another id. after entering data if i loguot and login from another id here wont show any data i have enter with previous id.

Advertisement

Answer

From Your Question it seems like you want to store some products under some user. which means A user can add many products and a product can have many users.. (many to many Relationship).

To achieve this You need an extra table named product_user which stores user_id and product_id.

Then In YOur User Model:

public function products(){
return $this->belongsToMany(Product::class);
}

Your Product Model:

public function users(){
return $this->belongsToMany(User::class);
}

Then in controller While adding Products to products table add this :

$user->products()->attach($product);//array..//

then You can access data like

 public function index()
{
    $user = Auth::user();
    $products = $user->products;
    $products = Product::latest()->paginate(1);

    return view('products.index',compact('products'))

        ->with('i', (request()->input('page', 1) - 1) * 5);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement