I'm building this application that has some dynamically generated filter's checkbox (in HTML, using PHP), so that the user can filter through what content he wants to see. The filters are by type, and category, and new categories can be added, and when added, they are dynamically added to the filter field. What i'm trying to do, is, if the user selects more than 1 category, it will show the content from both this categories. My controller for the filter is this:
if(isset($_POST['categorias'])){
$categorias = $_POST['categorias'];
}
if(isset($_POST['tipos'])){
$tipos= $_POST['tipos'];
}
And then i return
return view('home', ['filter' => json_encode($categorias), 'tipo' => $tipos]);
I'm trying to filter through the content like this:
$collection = DB::table('files')->where('categoria', 'like', '%' . $filter . '%')
->where('tipo', $tipo)
->take(8)
->get();
But nothing is returned... When i removed the "like" in the query, and only select 1 category, it works, and shows the content for that category, but i need the user to be able to select more than 1..
CodePudding user response:
This is making the assumption that $categories are an array of category names. Rather than using a like clause you can use whereIn to check against an array containing each of your category names.
// Decode your categories back into an array.
$categorias = json_decode( $filter );
// Use whereIn with your array of category names.
$collection = DB::table('files')->whereIn( 'categoria', $categorias )
->where('tipo', $tipo)
->take(8)
->get();