Laravel advance search filters with optional fields.

This post explains how to use the advanced filter with Laravel some fields are optional step by step.

Laravel advance filters with optinal value

In this above Image, have many fields and some are optional it’s depends on the user.

Step:1 Create a simple form 

 <form action="{{route('PostSearch')}} ">
     <div >
       <label ><strong >Eye color </strong></label>
          <div >
             <div >
               <select name=eye_color>
                  <option value="">Not Given</option>
                  <option value="Blue" >Blue</option>
                  <option value="Brown" >Brown</option>
                  <option value="Green">Green</option>
                  <option value="Hazel" >Hazel</option>
                  <option value="Grey" >Grey</option>
                  <option value="Dark brown">Dark brown</option>
                  <option value="Rather not say" >Rather not say</option>
                  <option value="Other">Other</option>
               </select>
             </div>
           </div>
     </div>



       <div >
           <label ><strong >Smoke </strong></label>
              <div >
               <div >
                 <select name=smoke>
                 <option value="" >Not Given</option>
                 <option value="No" >No</option>
                 <option value="Yes, socially" >Yes, socially</option>
                 <option value="Yes, regularly" >Yes, regularly</option>
                 <option value="Rather not say" >Rather not say</option>
                 </select>
               </div>
              </div>
            </div>



</form>

Step: 2 SearchController.php

 public function PostSearch(Request $request)
 {

     $filters = [
            'eye_color' => $request->eye_color,
            'drink'    => $request->drink,
        ];
     
      $user = User::where(function ($query) use ($filters) {
            if ($filters['eye_color']) {
                $query->where('eye_color', '=', $filters['eye_color']);
            }
             if ($filters['smoke']) {
                $query->where('smoke', '=', $filters['smoke']);
            }
        })->get();

    return $user;
  }

Here we try to show with two fields, the query filter eye_color  apply on the filter when user select. so here we complete the post on Laravel advance search filters with optional fields.