4
4

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

Laravel Eloquent firstWhere()到着

Last updated at Posted at 2020-01-17

Taylorさんをはじめ、Laravelに貢献する開発者が頑張っていて、だんだんと新しい機能を追加されています。今回(2020-01-15)リリースされたLaravel 6.11.0 に含まれている機能の一つをしょかいします。

firstWhere() の 機能をEloquentに

あるモデルを一意キーで検索する時、たとえばUserのemaiIlphonenumber など、下記のようなコードを使うと思います

    User::where('phonenumber', '12345')->first();

が このPRでこのための専用の関数firstWhere(キー、値)が追加され、上記のコードをこのように書けるようになりました!

    User::firstWhere('phonenumber', '12345');

便利ですね!今までこの機能はcollectionにふくまれていますが、これからEloquentのモデルに使えるようになりました!

### 注意点

現時点、この機能はEloquentのクエリー・ビルダーしか対応されていないので、残念ながらIlluminate\Database\Query\Builderクラスでは使えません。

つまり、下記のコードを実行すればエラーが発生します。

 DB::table('users')->firstWhere('phonenumber', '12345');
 // エラー

参照リンク

https://github.com/laravel/framework/compare/v6.10.1...v6.11.0
https://github.com/laravel/framework/pull/31089
https://laravel.com/docs/6.x/collections#method-first-where

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?