Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nerku's avatar
Level 1

search product by a category id in laravel

I need your help please!

I want to search product by a specific category id. I have 3 tables : Category [id, name ] Product [id, name, title] ProductCategory[id, product_id, category_id].

I have done all relationships.

I make this query::

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;


class SearchController extends Controller
{
    public function search(Request $request)
    {

		if($request->get('search-category')) {
			$products = Product::join('product_category', 'product.id', '=', 'product_category.product_id')
				->join('category', 'category.id', '=', 'product_category.category_id')
				->select('product.id', 'product.title', 'product.description', 'product.price')
                ->get(); 
		}
    	return view('search', compact('products'));
	}
}
0 likes
2 replies
nerku's avatar
Level 1

i need only condition 'where' for category id

PersonalHomePage's avatar

Something like this?

        if($request->get('search-category')) {
            $search = $request->get('search-category');
            $products = Product::join('product_category', 'product.id', '=', 'product_category.product_id')
                ->join('category', 'category.id', '=', 'product_category.category_id')->where('column_name','LIKE',"%$search%")
                ->select('product.id', 'product.title', 'product.description', 'product.price')
                ->get();
        }
        return view('search', compact('products'));

Please or to participate in this conversation.