SELECT 所有如果参数为 null 否则 return 特定项目 laravel

SELECT all if parameter is null else return specfic item laravel

我打算创建一个过滤器。如果参数为空 return 所有其他 return 特定项目。

title = "A" and body="B"  --> return all values where title like A & body like B
title = "" and body="B"  -->  return all values where body like B
title = "" and body=""  -->  return all values 

这是我的查询如何根据我的条件更改此查询

$posts =  Blog::where('title','LIKE',"%{$title}%")
            ->Where('body', 'LIKE',"%{$body}%")
            ->offset($start)
            ->limit($limit)
            ->orderBy($order,$dir)
            ->get();

根据您的条件更新您的查询构建器对象

$posts =  Blog::offset($start)
            ->limit($limit)
            ->orderBy($order,$dir);
if(!empty($title)){
    $posts = $posts->where('title','LIKE',"%{$title}%");
}

if(!empty($body)){
    $posts = $posts->where('body','LIKE',"%{$body}%");
}           
$posts = $posts->get();