Laravel conditional query

Example 1, using query builder on controller function

public function index()
{
    $state = Input::get('state');
    $site_name = Input::get('site_name');

    $query = DB::table('approvedsites')
            ->join('ref', 'approvedsites.state', '=', 'ref.code')
            ->select('approvedsites.*', 'ref.desc1')
           ;

    if (!empty($state)) {
        $query = $query->where('state','=',$state);
    }

    if (!empty($site_name)) {
        $query = $query->where('agname','LIKE',"%$site_name%");
    }

    $approvedsites = $query->get();
    
    //view raw sql query
    
    dd($query->toSql());
    dd(DB::getQueryLog());
}
 

Example 2, using static method on model

//controller function

public function index()
{
    $state = Input::get('state');
    $site_name = Input::get('site_name');     

		$filter_data = array('state' => $state,
					'site_name' => $site_name
					 );
                       
    $approvedsites = Approvedsite::getAllApprovedSites($filter_data)->get();                   
    
    //view raw sql query
    
    dd($query->toSql());
    dd(DB::getQueryLog());
}

//model function

public static function getAllApprovedSites($filter_data=array())
{
    $query = DB::table('approvedsites')
            ->join('ref', 'approvedsites.state', '=', 'ref.code')
            ->select('approvedsites.*', 'ref.desc1')
           ;

    if (isset($filter_data['state']) && !empty($filter_data['state'])) {
        $state = $filter_data['state'];
        $query = $query->where('state','=',$state);
    }

    if (isset($filter_data['site_name']) && !empty($filter_data['site_name'])) {
        $site_name = $filter_data['site_name'];
        $query = $query->where('agname','LIKE',"%$site_name%");
    }

    return $query;
}

Example 3 – Using scope method on model

//controller function

public function index()
{
    $state = Input::get('state');
    $site_name = Input::get('site_name');     

		$filter_data = array('state' => $state,
					'site_name' => $site_name
					);
                       
    $approvedsites = Approvedsite::filter($filter_data)->get();                  
    
    //view raw sql query
    
    dd($query->toSql());
    dd(DB::getQueryLog());
}

//model function

public function scopeFilter($query,$filter_data=array())
{
  if (isset($filter_data['state']) && !empty($filter_data['state'])) {
      $state = $filter_data['state'];
      $query->where('state','=',$state);
  }

  if (isset($filter_data['site_name']) && !empty($filter_data['site_name'])) {
      $site_name = $filter_data['site_name'];
      $query->where('agname','LIKE',"%$site_name%");
  }

  return $query;

}