4
10

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 3 years have passed since last update.

[Laravel] Eloquent::when() を使う

Posted at

when()メソッドを使う

例えば下記のように、if文を使ってクエリを書くコードがある。

sample.php
$query = User::query();

if(request('filter') == 'likes') {
    $query->where('likes', '>' , request('likes_amount', 0));
}

上記コードを、when()methodを使って、より見やすく、”Laravel Way”で書く。
when()メソッドの第一引数がtrueの場合実行される。

when_sample.php
$query = User::query();

$query->when($request('filter') == 'likes', function($q){
    return $q->where('likes', '>', request('likes_amount', 0));
});

$users = $query->get();

###その他例
Query Builderでも使える。

sample1.php

$users = DB::table('users')
          ->when($request->input('role'), function($q) use($role) {
              //イコールの場合、'='は省略可能
              return $q->where('role', $role)
          })->get();

参考

https://laravel.com/docs/8.x/queries#conditional-clauses
https://laraveldaily.com/less-know-way-conditional-queries/

4
10
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
4
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?