2
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 とPHP TipsAdvent Calendar 2023

Day 7

リクエストに値があったら検索条件に含める をワンライナーで書こう!!

Last updated at Posted at 2023-12-06

概要

実装されている検索機能で、このような処理を見かけます

$query = User::query;
if(!is_null($request->input('name') && $request->input('name') !== ""){
  $query->where('name',$request->input('name'));
}
$users = $query->get();

リクエストオブジェクトのwhenHasメソッドを使えばごちゃごちゃしてる所をワンライナーで書けるぜ!!!!

$query = User::query;
$request->whenFilled('name', fn (string $input) => $query->where('name',$name));
$users = $query->get();

Cooooooool

参考

2
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
2
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?