Laravel 5.6搜索其中

时间:2018-03-13 02:47:49

标签: laravel

这也很有用。但问题是当我没有搜索任何东西时,那里没有结果。我的意思是projects?startdate=&enddate=&search=那里没有结果。我只是不明白。为什么

$search = $request->get('search');
$startdate = $request->input('startdate');
$enddate = $request->input('enddate');
        $projects = $projects
            ->where(function ($query) use ($search) {
                $query->orWhere('lastname', 'like', '%'.$search.'%')
                    ->orWhereRaw("(firstname) LIKE '%$search%'")
                    ->orWhereRaw("(register) LIKE '%$search%'");
            })
            ->whereBetween('created_at', [$startdate, $enddate])
            ->orderBy("created_at", 'desc')
            ->paginate(10);
        return view('projects.index', compact('projects'));

2 个答案:

答案 0 :(得分:1)

当您不搜索任何内容时,$search$startdate$enddatenull
whereBetween()无法使用null值。

仅在变量具有值时才向查询添加约束:

$query = $projects->query();

if(!is_null($search)) {
    $query->where(function ($query) use ($search) {
        $query->orWhere('lastname', 'like', '%'.$search.'%')
            ->orWhere('firstname', 'like', '%'.$search.'%')
            ->orWhere('register', 'like', '%'.$search.'%');
    })
}

if(!is_null($startdate) && !is_null($enddate)) {
    $query->whereBetween('created_at', [$startdate, $enddate])
}

$projects = $query->orderBy("created_at", 'desc')->paginate(10);

请勿使用->orWhereRaw("(firstname) LIKE '%$search%'")之类的内容 这是一个巨大的安全风险: https://en.wikipedia.org/wiki/SQL_injection

答案 1 :(得分:0)

可能有两种可能的方式:

  1. 检查两个日期变量是否为空值,然后 将其附加到查询过滤器

    $startdate = $request->input('startdate');
    $enddate = $request->input('enddate');
    
    if(!is_null($startdate) && !is_null($enddate)) {
        $query->whereBetween('created_at', [$startdate, $enddate]
    }
    
  2. 或者,如果未提供默认值,则可以将其设置为日期范围 请求。

    /* if startdate value is null, it will set default date, as 1 year back from current date */
    $startdate = $request->input('startdate', Carbon::now()->subYears(1)); 
    
    /* if enddate value is null, it will set default date, as current date */
    $enddate = $request->input('enddate', Carbon\Carbon::now());