Home > Enterprise >  How To get Product Where Category Id Laravel
How To get Product Where Category Id Laravel

Time:01-09

Movie

  • id | Category_id |Name
  • 1 | 1 | Naruto
  • 2 | 2 | Boruto
  • 3 | 3 | Sakura

Category

  • id | parent_id |Name
  • 1 | | Anime
  • 2 | 1 | Action
  • 3 | 2 | Fantasy

How i get movie where category_id 1 all movie on child category will show

CodePudding user response:

I think for your issue, you need to change your structer. In your case the best structure for database should be a many to many relationship. A good example: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

CodePudding user response:

$categoryId=1; // searching category id
Movie::where('category_id',$categoryId)->get()

Additionally, if you make scope in Movie Model

Movie.php

 public function scopeInCategory($query,int $categoryId)
 {
    return $query->where('category_id', $categoryId);
 }

In your controller

$categoryId=1; // searching category id
Movie::inCategory()->get();

you can read more about query scopes from here.

  •  Tags:  
  • Related