$ php artisan make:model Role -m
migration file: user
Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->integer('role_id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });
migration file: role
Schema::create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); });
$ php artisan migrate:refresh
Model: Role.php
protected $fillable = [ 'name' ];
Model: User.php
public function role(){ return $this->belongsTo('App\Role'); }
$ php artisan make:middleware IsAdmin
Kernel.php
protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'role'=>\App\Http\Middleware\RoleMiddleware::class, 'IsAdmin'=>\App\Http\Middleware\IsAdmin::class, ];
insert into roles (name) values (‘administrator’);
insert into roles (name) values (‘subscriber’);
update users set role_id=1 where id=1;
User.php
public function isAdmin(){ if($this->role->name == 'administrator'){ return true; } return false; }
Route
Route::get('/', function () { $user = Auth::user(); if($user->isAdmin()){ echo "this user is adminstrator"; } // return view('welcome'); });
うまく権限の判定が上手く動いていたのを確認します
Middleware:IsAdmin.php
use Illuminate\Support\Facades\Auth; public function handle($request, Closure $next) { $user = Auth::user(); if($user->isAdmin()){ return redirect()->intended('/admin'); } return $next($request); }
Route
Route::get('/admin', 'AdminController@index');
$ php artisan make:controller AdminController
Controller:AdminController.php
class AdminController extends Controller { public function __construct(){ $this->middleware('IsAdmin'); } public function index(){ return "you are an administrator because you are seeing this page"; } }
Middleware:IsAdmin.php
use Illuminate\Support\Facades\Auth; public function handle($request, Closure $next) { $user = Auth::user(); if(!$user->isAdmin()){ return redirect()->intended('/'); } return $next($request); }
ロールを変更して、リダイレクトされるか確認します。
update users set role_id=2 where id=1;
ロールによって、表示を切り分けたいページのControllerでは、上記のように、AdminControllerで$this->middleware(‘IsAdmin’);の判定を行うか、もしくは、以下のようにルーティングでミドルウェアの判定を行います。
Route::get('/admin/user/roles', ['middleware'=>['IsAdmin',], function(){ return "Middleware role"; }]);
出し分ける場合、Controllerで毎回if文を書くのではなく、middlewareに関数を書いて、それを読み込むのですね。
ロールを別テーブルでbelongsToとしていますが、ロールがUserテーブルの場合でも、ロジックは同じだと思います。