1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravelで絞り込み検索に役立つ構文

Last updated at Posted at 2022-12-20

この記事について

キーワード検索+日付絞り込み+ソートなど複雑な絞り込みを行う際に条件を保持したり、eroquentの条件分岐をどう実装するかの備忘録

絞り込みSQL

「●●の時にwhere句をくっつける」

$keywordが存在している時、where句による絞り込みを行う。

when(isset($keyword),function($query) use($keyword){
    return $query->where("name","LIKE","%" . $keyword . "%")
});

「( A or B ) or ( C and D )などの括弧付き条件を実装するには?」

$users->where(function($query){
    return $query->where("条件A")->orWhere("条件B");
})->orWhere(function($query){
    return $query->where("条件C")->where("条件D");
});

「実例」

例)日報一覧のうち、「日付」が指定されていた場合、日付で絞り込み、さらに、キーワードが入力されていた場合、「案件ID,案件名,顧客名」のいずれかで絞り込みを行いたい。

$assign["reports"] = ViewReport::when(isset($req->date), function($query) use ($date){
    return $query->where(function($query) use ($date){
        return $query->where("date",$date);
    });
})
->when(isset($req->key), function($query) use ($key){
    return $query->where(function($query) use ($key){
        return $query->where("project_id",$key)->orWhere("project_name","LIKE","%".$key."%")->orWhere("clients_name","LIKE","%".$key."%");
    });
})
->paginate(10);

ページングした際に検索条件を保持

通常のページング

{{ $projects->links('pagination::bootstrap-4') }}

条件を保持する書き方

{{ $projects->appends(request()->query())->links('pagination::bootstrap-4') }}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?