15
8

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のモデルにスコープクエリをぶち込んでおく

Posted at

#scopeHogeとscopeOfHogeを使う

Book.php
class Book extends Model
{
...
 public function scopeOfCode($query,$code){
     return $this->where('code',$code)->firstOrFail();
 }
}

こんなふうに書くことで、findOrFailと同じように使えるクエリが増える。

BookController.php
public function book($code){
       $book = book::ofCode($code);
       return view('book.book',[
           'book' => $book
       ]);   
}

scopeActive (scopeHoge)型

Userモデルのactiveチェックなどに役立つ。

User.php
public function scopeActive($query)
{
     return $query->where('active', 1);
}

使用例

$user = User::active()->get();

scopeOfType (scopeOfHoge)型

scopeActiveみたいな時に、引数がほしい時に使える。

Book.php
class Book extends Model
{
...
 public function scopeOfCode($query,$code){
     return $this->where('code',$code)->firstOrFail();
 }
}

もちろん、引数は初期値を入れれる。

Book.php
class Book extends Model
{
...
 public function scopeOfCode($query,$code = 1){
     return $this->where('code',$code)->firstOrFail();
 }
}

whereクエリでおわらすことも当然可能。

Book.php
class Book extends Model
{
...
 public function scopeOfCode($query,$code = 1){
     return $this->where('code',$code);
 }
}

僕は、使い勝手がいいので、firstOrFailを利用して、findOrFailの様に利用しています。
DBのunique設計にもよるのかな。まあ、書くコードかなり減ったからよし。

15
8
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
15
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?