skip to Main Content

I need to filter categories by name. Category name is stored in separated table category_details. When i listing this in blade all is good but when i need to filter it its show

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘details.name’
in ‘where clause’

Controller method

   public function index(Request $request)
    {
        $categories = Category::with('details')
            ->when($request->has('name'), function ($q) use ($request) {
                return $q->where('details.name', 'like', $request->query('name') .'%');
            })
            ->paginate(15);
        
       

           return view('ecommerce::admin.catalog.category.index', compact('categories'));
    }

Here is model method

 public function details()
 {
     return $this->hasOne(CategoryDetails::class, 'category_id', 'category_id');
 }

How can i achive this?

2

Answers


  1. Chosen as BEST ANSWER

    Fixed

    public function index(Request $request)
        {
            $categories = Category::with('details')
                ->when($request->has('name'), function ($q) use ($request) {
                    return $q->whereHas('details', function ($query) use ($request) {
                        return $query->where('name', 'like', '%'. $request->query('name') .'%');
                    });
                })
                ->paginate(15);
    
            $filter_categories = Category::with(['details', 'childrenRecursive'])->where('parent_id', '=', null)->get();
    
            return view('ecommerce::admin.catalog.category.index', compact('categories', 'filter_categories'));
        }
    

  2. Laravel has a function for this.
    You can simply use whereRelation. (Laravel docs)

        public function index(Request $request)
    {
        $categories = Category::with('details')
            ->whereRelation('details', 'name', 'like', $request->query('name') . '%')
            ->paginate(15);
    
        return view('ecommerce::admin.catalog.category.index', compact('categories'));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search