LoginSignup
3
4

More than 3 years have passed since last update.

【Laravel・Eloquent】modelの関数名になぜscopeをつけるのか

Posted at

scopeの定義方法

class Hoge extends Model {
  public function scopeFuge($query, $code) {
    //処理
  } 
}

関数名にscopeを追加し、引数$query$code(引数名は自由)を定義します。

引数

$queryとは

この引数は、whereで取得されるのと同じBuilderインスタンスが渡されます。

$code(引数名は自由)

コントローラから渡された引数がこの値に代入されます。

Person.php(Model)


class Person extends Model {

    public function scopeNameEqual($query, $str) 
        {
            return $query->where('name', $str);
        }
}

PersonController.php(Controller)


use App\Person;

class PersonController extends Controller {

    public function search(Request $request) {
        $item = Person::nameEqual($request->input)->first();
        //〜その他処理は割愛〜
        return view('person.find, $param);
    }
}

scopeを呼び出す時は、関数名のscopeを省略します。

なぜscopeを使うのか

scopeを使うことにより、上記の2つの引数が利用できるようになります。

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