1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

laravel middleware ルーティングで管理者だけを通したい

Last updated at Posted at 2024-02-03

やりたい事

web.phpの以下のコードででログインしていないアカウントを弾いてくれる。

->middleware('auth')

同じようにルーティング時点で管理者以外も弾きたい。

userテーブルにis_adminを追加

マイグレーション
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('is_admin')->after('remember_token')->nullable()->comment('管理者');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('is_admin');
        });
    }
};

middleware作成

 php artisan make:middleware AdminOnly
app/Http/Middleware/AdminOnly.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\User;

class AdminOnly
{
    public function handle(Request $request, Closure $next): Response
    {
        $is_admin = auth()->user()->is_admin;
        if($is_admin != 1){
            return redirect()->route('top');
        }

        return $next($request);
    }
}


Kernelに追加

app/Http/Kernel.php
    protected $routeMiddleware = [
        'adminOnly' => \App\Http\Middleware\AdminOnly::class,
    ];

やりたい事

これでis_adminフラグが立ってないユーザーを弾いてくれます。

web.php
->middleware(['auth', 'adminOnly'])
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?