Laravel advance search filters with optional fields.

Brijpal Sharma
laravel   Publish on:-March 27th, 2019 , Category:- Web Development


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' => Input::get('eye_color'),
            'drink'    => Input::get('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 post on Laravel advance search filters with optional fields.


Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...


0 Comments

You must be logged in to post a comment.