0

I have two table

  1. Menu
  2. Products

there structures are:

Menu:

id | product_id | user_id 

Product:

id | title | price| user_id

issue is i want to show add button if product is added in menu table by the specific user and if product is already added then i have to show remove button to remove data from menu table instead of add button.

 $product = Product::where(['user_id'=>$userID])->with('ProductImages')->get();
 $menuPlanner=Menu::where(['user_id'=>auth()->user()->id])->get();  
 $html =  view('frontend.dashboard.menu.available_items', ['products'=>$product,'menu_planner'=>$menuPlanner])->render();
 echo json_encode(array('products' => $html));

Is there any way in laravel to achieve this without any loop in view.

user3653474
  • 3,393
  • 6
  • 49
  • 135
  • I would rather suggest to make an inner join between the 2 tables and an easy foreach loop in the view blade file to do this. – nice_dev Jul 31 '21 at 15:08
  • @nice_dev: is there any way to achieve this using relation because my project is fully based on eloquent – user3653474 Jul 31 '21 at 16:30
  • Yes, of course. See https://stackoverflow.com/questions/23910553/laravel-check-if-related-model-exists – nice_dev Jul 31 '21 at 16:34

1 Answers1

0

The product model does not have any field that refers to the user, so here you will get an error

$product = Product::where(['user_id'=>$userID])->with('ProductImages')->get();

You have a table called "menu" that acts as a pivot so you have a relation of many to many

I recommend that you read the Laravel documentation, explains how to build this type of relationship. it's pretty straightforward, hope this helps you.

https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

Randy
  • 23
  • 4
  • Thanks for the answer I have user_id column in product table but how will I know whether this product is already added in the menu planner table by user who is logged in through relation and use that status/flag to show in my view. – user3653474 Jul 31 '21 at 18:40
  • Once you have created the relationship you can do the following. $user = User::find(1); $exists = $user->menu->contains($product_id); – Randy Aug 01 '21 at 09:58