Viewed   101 times

I have a search form with multiple input and select boxes I need help to get if conditions in my query in order to each part works separately and all at once.

here is my blade codes:

<form action="{{route('advancesearch')}}" method="post">
      {{csrf_field()}}
      <div class="sidebar-title">
        <span>Advanced Search</span>
        <i class="fa fa-caret-down show_sidebar_content" aria-hidden="true"></i>
      </div>
      <!-- ./sidebar-title -->

      <div id="tags-filter-content" class="sidebar-content">
        <div class="filter-tag-group">

          @foreach($options as $option)
          <div class="tag-group">
            <p class="title">
              <span class="filter-title show_filter_content">{{$option->title}} <span class="pull-right"><i class="fa fa-minus"></i></span></span>
            </p>
            <div class="filter-content">
              <div class="checkbox">
              @foreach($option->suboptions as $suboption)
              <label for="suboptions">
                <input name="suboptions[]" type="checkbox" value="{{$suboption->id}}">
                {{ucfirst($suboption->title)}}
              </label>
              @endforeach
            </div>
          </div>
          </div>
          @endforeach
          <!-- ./tag-group -->

          <div class="tag-group">
            <p class="title">
              <span class="filter-title show_filter_content">Brand <span class="pull-right"><i class="fa fa-minus"></i></span></span>
            </p>
            <div class="filter-content">
              <div class="checkbox">
              @foreach($brands as $brand)
              <label for="brands">
                <input name="brands[]" type="checkbox" value="{{$brand->id}}">
                {{$brand->title}}
              </label>
              @endforeach
            </div>
          </div>
          </div>
          <!-- ./tag-group -->

          <div class="tag-group">
            <p class="title">
              <span class="filter-title show_filter_content">Price Range <span class="pull-right"><i class="fa fa-minus"></i></span></span>
            </p>
            <div class="row filter-content">
              <div class="col-md-6">
                <div class="form-group">
                  <label for="min_price" hidden>Min</label>
                  <input type="text" name="min_price" class="form-control" placeholder="Rp Min">
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-group">
                  <label for="max_price" hidden>Max</label>
                  <input type="text" name="max_price" class="form-control" placeholder="Rp Max">
                </div>
              </div>
            </div>
          </div>
          <!-- tag-group -->

          <div class="text-center mt-20">
            <button type="submit" class="btn btn-danger">TERPAKAN</button>
          </div>

        </div><!-- ./filter-tag-group -->
      </div><!-- ./sidebar-content -->
    </form>

and this is my route:

Route::post('/advanced-search', 'frontendSearchController@filter')->name('advancesearch');

finally my function code is:

public function advancedsearch(Request $request) {
        $brands = Brand::all(); // uses for other part of the page. (not related to search function)
        $options = Option::all(); // uses for other part of the page. (not related to search function)
        $suboptions = DB::table('product_suboption'); // where my product_id and subopyion_id saves

        //search function
        $products = Product::where(function($query){
            //getting inputs
            $suboptions2 = Input::has('suboptions') ? Input::get('suboptions') : [];
            $min_price = Input::has('min_price') ? Input::get('min_price') : null;
            $max_price = Input::has('max_price') ? Input::get('max_price') : null;
            $brands2 = Input::has('brands') ? Input::get('brands') : [];

            //returning results
            $query->where('price','>=',$min_price)
                    ->where('price','<=',$max_price);
            })->get();

        return view('front.advancesearch', compact('products', 'brands', 'options'));
    }

My models relations:

product model:

public function options(){
     return $this->belongsToMany(Option::class);
  }
  public function suboptions(){
     return $this->belongsToMany(Suboption::class, 'product_suboption', 'product_id', 'suboption_id');
  }
public function brand(){
     return $this->belongsTo(Brand::class);
  }

Option model:

public function suboptions(){
     return $this->hasMany(Suboption::class, 'option_id');
  }

  public function products(){
     return $this->belongsToMany(Product::class);
  }

Suboption model:

public function option(){
     return $this->belongsTo(Option::class, 'option_id');
  }

  public function products(){
     return $this->belongsToMany(Product::class);
  }

Brand model:

public function products(){
     return $this->hasMany(Product::class);
}

note

My brands search is coming from products table where I have column brand_id for each product.

BUT

My suboptions come from 3rd table named product_suboption (as you see in my models codes) where i save product_id and suboption_id.

 Answers

2

SOLVED

After weeks of playing with codes finally I came to the right results for myself (in my case it works this way for others maybe works with other suggested answers)

public function advancedsearch(Request $request) {
    $options = Option::all();
    $brands = Brand::all();
    $brandss = Input::has('brands') ? Input::get('brands') : [];
    $suboption = Input::has('suboptions') ? (int)Input::get('suboptions') : [];
    $min_price = Input::has('min_price') ? (int)Input::get('min_price') : null;
    $max_price = Input::has('max_price') ? (int)Input::get('max_price') : null;

    //codes
    if(count($request['suboptions'])){
      $products = DB::table('products')
      ->join('product_suboption', function ($join) {
        $suboption = Input::has('suboptions') ? Input::get('suboptions') : [];
            $join->on('products.id', '=', 'product_suboption.product_id')
                 ->where('product_suboption.suboption_id', '=', $suboption);
        })
      ->paginate(12);
    }

    elseif(count($request['brands'])){
      $products = DB::table('products')
      ->whereIn('products.brand_id', $brandss)
      ->paginate(12);
    }

    elseif(count($request['min_price']) && count($request['max_price'])){
      $products = DB::table('products')
      ->whereBetween('price', [$min_price, $max_price])
      ->paginate(12);
    }


    return view('front.advancesearch', compact('products', 'brands', 'options'));
    }

NOTE: most of my pricing issues solved with (int) as you see in my codes (int)Input::get('min_price') and (int)Input::get('max_price').

Special thanks to Ravindra Bhanderi for his count($request[''] suggestion.

Monday, November 7, 2022
 
4

I didn't try this code but its should work under laravel 4.2.

$query = DB::table('rooms')
        ->join("salereservation", "salereservation.room_id", "=", "rooms.room_id")
        ->join("customers", "customers.id", "=", "salereservation.customer_id")
        ->where("salereservation.sale_status",'=',1)
        ->select('rooms.*', 'salereservation.*', 'customers.*');

if($fname!=''){
    $query->where("fname",'like',"%$fname%");
}

if($lname!=''){
    $query->where("lname",'like',"%$lname%");
}
if($time_in!=''){
   $query->where("start_datetime",'like',"%$time_in%");
}
if($time_out!=''){
    $query->where("end_datetime",'like',"%$time_out%");
}
if($phone!=''){
    $query->where("phone",'like',"%$phone%");
}
if($room_no!=''){
  $query->where("room_no",'like',"%$room_no%");
}
$data = $query->get(); //finally get the result

Update:

For query verification you can print your query using:

 $queries = DB::getQueryLog();
 $last_query = end($queries);
 dd($last_query);

And verify if your query different from your desired query. If something went to different we can upgrade our query structure according to them.and also can you update with your latest query generated from laravel methods.

But if you still face some difficulties to understand my point of view. let me know.

Friday, September 16, 2022
 
4

You can achieve what you need by reverting the constraints on last_day and first_day - this way there is no need to use NOT clause.

Instead of doing

WHERE NOT(`last_day` <= '2001-06-01' OR `first_day` >= '2022-12-01');

you can do

WHERE `last_day` > '2001-06-01' AND `first_day` < '2022-12-01';

And with Eloquent builder the following should do the trick:

$query = $query->where('last_day', '>', $first_day)->where('first_day', '>', $last_day);
Tuesday, October 18, 2022
1

You need to change:

if ($name)
   $query->where('first_name', 'like', "$name%")->orWhere('last_name', 'like', "$name%");

into:

if ($name) {
   $query->where(function($q) use ($name) {
         $q->where('first_name', 'like', "$name%")->orWhere('last_name', 'like', "$name%");
   });
}

to make Laravel to add parentheses so it will work as you expect.

EDIT

Of course you don't need to wrap everything with closure here, so the best solution for that would be:

<?php

$query = DB::table('mytable')->select('id', 'first_name', 'last_name');

if ($name) {
    $query->where(function ($q) use ($name) {
        $q->where('first_name', 'like', "$name%")
            ->orWhere('last_name', 'like', "$name%");
    });
}
if ($specialty_s) {
    $query->where('primary_specialty', $specialty_s);
}
if ($city_s) {
    $query->where('city', $city_s);
}
if ($state_s) {
    $query->where('state_province', $state_s);
}
if ($lundbeck_id_s) {
    $query->where('customer_master_id', $lundbeck_id_s);
}
if ($degree_s) {
    $query->where('primary_degree', $degree_s);
}

$data = $query->get();
Saturday, December 10, 2022
 
5

How do I write a select with Laravel query builder for the above columns?

You can do:

$data = DB::table('mytable')
        ->join('myothertable', 'mytable.id', '=', 'myothertable.mytable_id')
        ->select(
            'mytable.id',
            'mytable.column1',
            'mytable.another_column',
            'mytable.created_at',
            'myothertable.id'
        )
        ->get();

You can read the documentations here

Monday, August 22, 2022
 
bozho
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :