端くれプログラマの備忘録 Laravel [Laravel] Scopeの使い方

[Laravel] Scopeの使い方

頻繁に使う条件はScopeとして定義しておくことで、再利用が容易になる。

実装

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Scope a query to only include popular users.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    /**
     * Scope a query to only include active users.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }

    /**
     * Scope a query to only include users of a given type.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOfType($query, $type)     //引数を取るScopeも定義できる
    {
        return $query->where('type', $type);
    }
}

使い方

$users = App\User::popular()->active()->orderBy('created_at')->get();
$users = App\User::ofType('admin')->get();

参考サイト

Eloquent: Getting Started – Laravel – The PHP Framework For Web Artisans
http://laravel.com/docs/5.1/eloquent#query-scopes