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

Alex Fts's avatar

I want to use search query in my many to many relation!

Business Model:

        public function cat()
        {
            return $this->belongsToMany(BusinessCategory::class, 'cat_business',  'business_id' , 'cat_id');
        }

BusinessCategory Model:

    public function business()
    {
        return $this->belongsToMany(Business::class, 'cat_business','business_id', 'cat_id' );
    }

Search Query:

    public function search(Request $request){
        // Get the search value from the request

        $search = $request->input('search');
        $catsearch = $request->input('category');
        $location = $request->input('location');

        // Search in the title and body columns from the posts table
        $business = Business::query()

             ->where('name', 'LIKE', "%{$search}%")
             ->where('???', 'LIKE', "%{$catsearch}%")
             ->where('address', "%{$location}%")
            ->get();

            dd($business);
        // Return the search view with the resluts compacted
        return view('frontend.search', compact('business'));
    }
0 likes
9 replies
tykus's avatar
tykus
Best Answer
Level 104

@alex fts you don't specify which column you want to search on the business_categories table - assuming name below (but swap as needed):

$business = Business::query()
    ->where('name', 'LIKE', "%{$search}%")
    ->where('address', "%{$location}%")
    ->whereHas('cat', fn ($query) => $query->where('name',  'LIKE', "%{$catsearch}%"))
    ->get();
Alex Fts's avatar

@tykus How can I retrive all business with the category id

    public function SingleCategory($id)
    {
        $category = BusinessCategory::find($id);
         $result = $category->business->all();
         dd($result);
        return view('FrontEnd.category', compact('category', 'result'));
    }
tykus's avatar

@Alex Fts that should work - you also can eager-load the related Businesses:

    public function SingleCategory($id)
    {
        $category = BusinessCategory::with('business')->find($id);
        return view('FrontEnd.category', compact('category'));
    }

Now, the BusinessCategory instance will have business property; which is a Collection of Business instances:

@foreach($category->business as $bus)
	{{ $bus->name }}
@endforach

Aside, your relation would be more readable as plural businesses

Alex Fts's avatar

@tykus it is not giving exact results against every category it shows business against id 1 or 2 but for further it shows the blank array (the businesses against id 1 or 2 are also incorrect)

#attributes: array:6 [▼
    "id" => 3
    "name" => "Tech"
    "created_at" => "2022-05-06 13:41:03"
    "updated_at" => "2022-05-06 13:41:03"
    "icon" => "1651844463_briefcase.png"
    "image" => "1651844463_discover-horize.webp"
  ]
  #original: array:6 [▶]
  #changes: []
  #casts: []
  #classCastCache: []
  #attributeCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:1 [▼
    "business" => Illuminate\Database\Eloquent\Collection {#603 ▼
      #items: []
      #escapeWhenCastingToString: false
    }
  ]
Alex Fts's avatar

@tykus But in My Table

id		business_id		cat_id	 created_at		updated_at	
1				1	   				   2					NULL				NULL	
2				1					   3				    NULL				NULL	
3				2					    1					NULL			   NULL	
4				2					   4			    	NULL				NULL	
5				3					    5					NULL				NULL	
6				3						6					NULL				NULL	
tykus's avatar

Your relationship is wrong:

public function business()
{
    return $this->belongsToMany(Business::class, 'cat_business', 'cat_id', 'business_id');
}
1 like
MohamedTammam's avatar
$business = Business::query()
			->whereHas('cat', function($q) use ($catsearch) {
				$q->where('title', "%{$catsearch}%");
				return $q;
			})
             ->where('name', 'LIKE', "%{$search}%")
             ->where('address', "%{$location}%")
            ->get();
tykus's avatar

@MohamedTammam a few things are off compared to my solution above (i) the relation is named cat, (ii) pass $catsearch into the Closure scope, and (ii) no need to return $q inside the Closure;

1 like

Please or to participate in this conversation.