0

Struggling to figure out how to filter data in view using checkboxes. If only one location is selected, then it's straightforward. But what if multiple locations are selected? Is this a @foreach?

My view

<form method="post" action="filter">    
{{ csrf_field() }}
<input type="checkbox" name="locationfilter[]" value="Chicago">Chicago</label>
<input type="checkbox" name="locationfilter[]" value="New York">New York</label>
<button type="submit" class="btn btn-primary"> Submit </button>

My controller

$lofilter = implode(", ", $request->get('locationfilter'));
$mypostings = Postings::where('location', 'LIKE', '%'. $lofilter .'%')->get();
3
  • Are you trying to filter the locations in the view or the controller? Commented Nov 27, 2017 at 6:17
  • u want locations filtered with Or condition? Commented Nov 27, 2017 at 6:19
  • whereIN condition will work for comma separated match in Laravel. Commented Nov 27, 2017 at 6:40

1 Answer 1

3

You can use whereIn() function to get values from given array,

users = DB::table('users')->whereIn('id', [1, 2, 3])->get();

if you want to use LIKE operator try like this,

$checkbox = []; //assume this array as selected checkboxes
DB::query()
->Where(function ($query) use($checkbox) {
    for ($i = 0; $i < count($checkbox ); $i++){
          $query->orwhere('location', 'like',  '%' . $checkbox [$i] .'%');
    }  
})->get();   
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry I'm beginner in laravel & eloquent but shouldn't be $query->where instead of $query->orwhere?
@CasperSL I finally get it, I know I'm slow but I'm 50 years old :) ! You have used orwhere because you will have a lot's of "wheres" due to the for cycle and you have to get all the incidences :) Thank you again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.