PHP
model
laravel

addGlobalScopeを使って分かりやすいソースコードを書きましょう

More than 1 year has passed since last update.
Members
 | ID | name  | role   | email 
 |-------------------------
 | 1  | 一郎  | admin  | itiro@test.com
 | 2  | 次郎  | guest  | jirou@test.com
 | 3  | 三郎  | admin  | saburou@test.com

以前の書き方:

old_version.php
$admin = Memeber::where('role', 'admin')->get();
$guest = Memeber::where('role', 'guest')->get();

現在の書き方:

new_version.php
$admin = Admin::all();
$guest = Guest::all();
App\Member.php
class Member extends Model
{
    protected $table = 'members';
}
App\Admin.php
use App\Member;
use Illuminate\Database\Eloquent\Builder;

class Admin extends Member
{
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('role_admin', function(Builder $builder) {
            $builder->where('role', 'admin');
        });
    }
}
App\Guest.php
use App\Member;
use Illuminate\Database\Eloquent\Builder;

class Guest extends Member
{
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('role_guest', function(Builder $builder) {
            $builder->where('role', 'guest');
        });
    }
}

以上です。

感想

グローバルスコープを利用して、明示的なモデル名を使えば、ソースコードがもっと分かりやすくなります。