通过 json_encode 变量查询 Laravel Eloquent

Query through json_encode variable in Laravel Eloquent

我正在构建这个应用程序,它有一些动态生成的过滤器复选框(在 HTML 中,使用 PHP),以便用户可以过滤他想看的内容。过滤器是按类型和类别分类的,可以添加新类别,添加时动态添加到过滤器字段中。 我想做的是,如果用户 select 超过 1 个类别,它将显示这两个类别的内容。我的过滤器控制器是这样的:

    if(isset($_POST['categorias'])){
        $categorias = $_POST['categorias'];
    } 
    if(isset($_POST['tipos'])){
        $tipos= $_POST['tipos'];
    }

然后我return

    return view('home', ['filter' => json_encode($categorias), 'tipo' => $tipos]); 

我正在尝试像这样过滤内容:

$collection = DB::table('files')->where('categoria', 'like', '%' . $filter . '%')
                                ->where('tipo', $tipo)
                                ->take(8)
                                ->get();   

但什么都没有 returned...当我删除查询中的“喜欢”时,只有 select 1 个类别,它有效,并显示该类别的内容,但是我需要用户能够 select 超过 1..

这是假设 $categories 是一个类别名称数组。您可以使用 whereIn 来检查包含每个类别名称的数组,而不是使用 like 子句。

// 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();