Laravel Eloquent: 在 where like 子句中添加变量(未定义变量)

Laravel Eloquent: adding variable inside where like clause (undefined variable)

$search_category = "Gen";
$all_categories = HmsBbrCategory::query()
    ->when(empty($search_category), function ($query) {
        $query->where('category_id', '>=', '1');
    })
    ->when(!empty($search_category), function ($query) {
        $query->where('category_name', 'LIKE', "%$search_category%");
    })
    ->orderBy('category_id', 'ASC')
    ->get();

my !empty() 将触发,因为 $search_category 有一个值。我还需要在 LIKE %%.

中使用相同的 $search_category

加上 'LIKE', "%$search_category%" 得到 "message": "Undefined variable: search_category",

如何修复未定义的变量

这是因为变量的作用域。您的变量不存在于回调范围内。使用 use 关键字将其传递到那里:

->when(!empty($search_category), function ($query) use ($search_category) {
    $query->where('category_name', 'LIKE', "%$search_category%");
});