MENU

問い合わせ

    お問い合わせ


    【Laravel+Vue.jsで作る管理画面をECSで動かす 第3回】ロールと Policy:誰が何をできるかをコードで決める

    社内向けの管理画面では、「営業担当は顧客を登録・編集できるが削除はできない」「経理の閲覧担当は見るだけ」のように、人によってできる操作を分けるのが普通です。今回は、Laravel 12 の Policy(=「誰がどのデータに何をしてよいか」を書くクラス)を使って、ロール(役割)ごとの権限を実装します。

    「閲覧だけの人には、登録ボタンや削除ボタンを見せなければ十分では?サーバー側で何をすればいいのか、どこまで作れば安全なのかが分からない…」

    結論から言うと、ボタンを隠すのは「使いやすさ」のための補助で、権限チェックの本体はサーバー側の認可(Policy)です。ボタンが無くても、URL を直接たたけばリクエストは届きます。Laravel では Policy に「誰が何をできるか」を1か所にまとめ、コントローラー・FormRequest・画面の表示制御のすべてがその判定を使うようにします。

    (2026年10月29日 追記:記事どおりに再現できるよう、必要なコードと手順を追加しました)

    前回(第2回:顧客マスタの一覧と登録)では、顧客マスタの一覧・登録・編集・削除と入力チェックを作りました。今回は、そこに「誰が操作してよいか」を加えます。新しく作るファイルは全文を、すでにあるファイルは変更箇所を差分で載せています。

    目次

    ロールと Policy で権限を分ける仕組み

    今回決める権限表

    最初に、ロールごとにできることを表にします。コードはこの表をそのまま写す形で書きます。

    操作管理者(admin)担当者(staff)閲覧のみ(viewer)
    顧客一覧を見るできるできるできる
    顧客を登録するできるできるできない(403)
    顧客を編集するできるできるできない(403)
    顧客を削除するできるできない(403)できない(403)

    403 は「ログインはしているが、その操作の権限が無い」ことを表すHTTPのステータスコードです。

    認可の流れ

    • ロールはユーザーごとに1つ:users テーブルに role 列を追加し、PHP の enum(=決まった値しか取れない型)で扱います。
    • 判定は Policy に集約:CustomerPolicy に「登録できるのは担当者」のようなルールを書きます。管理者は Gate::before で一括して許可します。
    • サーバー側で必ず判定:コントローラーでは Gate::authorize()、FormRequest では authorize() から Policy を呼び、許可されなければ 403 を返します。
    • 画面には判定結果だけを渡す:Vue 側では、サーバーが計算した「登録できるか」「この行を編集できるか」の true / false を見てボタンを出し分けます。画面側でロール名を見て判断するコードは書きません。

    📰 出典:Laravel 12.x Authorization

    ロールを enum で定義し、users テーブルに追加する

    app/Enums/Role.php

    app/Enums/Role.php を新しく作ります。

    <?php
    
    // app/Enums/Role.php
    
    declare(strict_types=1);
    
    namespace App\Enums;
    
    /**
     * ユーザーのロール。DB には value(admin / staff / viewer)を文字列で保存する。
     */
    enum Role: string
    {
        case Admin = 'admin';   // 管理者:すべての操作
        case Staff = 'staff';   // 担当者:登録・編集まで(削除は不可)
        case Viewer = 'viewer'; // 閲覧のみ
    
        public function label(): string
        {
            return match ($this) {
                self::Admin => '管理者',
                self::Staff => '担当者',
                self::Viewer => '閲覧のみ',
            };
        }
    }

    ロールを 'admin' のような文字列のまま扱うと、'Admin' や 'adimn' のような書き間違いがあっても気づけません。enum にしておくと、存在しないロールを書いた時点でエラーになります。

    マイグレーション:既定は「閲覧のみ」

    database/migrations/2025_06_10_000000_add_role_to_users_table.php を新しく作ります。

    <?php
    
    // database/migrations/2025_06_10_000000_add_role_to_users_table.php
    
    declare(strict_types=1);
    
    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): void {
                // 既定は最も弱い権限(閲覧のみ)。権限の付与は管理者が明示的に行う
                $table->string('role', 20)->default('viewer')->after('email');
            });
        }
    
        public function down(): void
        {
            Schema::table('users', function (Blueprint $table): void {
                $table->dropColumn('role');
            });
        }
    };

    既定値は、最も権限の弱い viewer にしました。新しく作られたユーザーが、うっかり編集や削除をできる状態で始まらないようにするためです(最小権限の原則)。

    User モデル:enum にキャストし、$fillable には入れない

    スターターキットの app/Models/User.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/app/Models/User.php
    +++ b/app/Models/User.php
    @@ -2,6 +2,7 @@
     
     namespace App\Models;
     
    +use App\Enums\Role;
     // use Illuminate\Contracts\Auth\MustVerifyEmail;
     use Illuminate\Database\Eloquent\Factories\HasFactory;
     use Illuminate\Foundation\Auth\User as Authenticatable;
    @@ -14,6 +15,7 @@ class User extends Authenticatable
     
         /**
          * The attributes that are mass assignable.
    +     * role は含めない(プロフィール更新などの画面から自分の権限を書き換えられないようにする)
          *
          * @var list<string>
          */
    @@ -23,6 +25,15 @@ class User extends Authenticatable
             'password',
         ];
     
    +    /**
    +     * 新規作成時の既定値(DB の既定値と合わせる。保存直後のインスタンスでも role を参照できるように)
    +     *
    +     * @var array<string, string>
    +     */
    +    protected $attributes = [
    +        'role' => 'viewer',
    +    ];
    +
         /**
          * The attributes that should be hidden for serialization.
          *
    @@ -43,6 +54,7 @@ protected function casts(): array
             return [
                 'email_verified_at' => 'datetime',
                 'password' => 'hashed',
    +            'role' => Role::class,
             ];
         }
     }

    casts() に Role::class を書くと、$user->role が文字列ではなく Role::Staff のような enum の値として取り出せます。

    📰 出典:Laravel 12.x Eloquent: Mutators & Casting(Enum Casting)

    大事なのは、role を $fillable に入れないことです。スターターキットのプロフィール更新画面は fill($request->validated()) で保存しますが、もし $fillable に role があり、FormRequest のルールにも誤って role を加えてしまうと、利用者が自分で自分を管理者にできる穴になります。権限を変える処理は、管理者だけが使う専用の処理として別に作るのが安全です。

    CustomerPolicy と Gate::before で権限を判定する

    app/Policies/CustomerPolicy.php

    app/Policies/CustomerPolicy.php を新しく作ります。

    <?php
    
    // app/Policies/CustomerPolicy.php
    
    declare(strict_types=1);
    
    namespace App\Policies;
    
    use App\Enums\Role;
    use App\Models\Customer;
    use App\Models\User;
    
    /**
     * 顧客マスタの認可ルール。
     * 管理者(admin)は AppServiceProvider の Gate::before ですべて許可しているため、ここには出てこない。
     */
    class CustomerPolicy
    {
        /** 一覧を見る:ログインしていれば全ロール可 */
        public function viewAny(User $user): bool
        {
            return true;
        }
    
        /** 登録する:担当者のみ(閲覧のみは不可) */
        public function create(User $user): bool
        {
            return $user->role === Role::Staff;
        }
    
        /** 編集する:担当者のみ */
        public function update(User $user, Customer $customer): bool
        {
            return $user->role === Role::Staff;
        }
    
        /** 削除する:管理者のみ(担当者・閲覧のみは不可) */
        public function delete(User $user, Customer $customer): bool
        {
            return false;
        }
    }

    Laravel は、App\Models\Customer に対して App\Policies\CustomerPolicy という名前のクラスがあれば、自動的に対応づけます(登録のコードは不要です)。update と delete が Customer $customer を受け取っているのは、将来「自分が担当する顧客だけ編集できる」のようなルールに広げられるようにするためです。

    Gate::before:管理者はすべて許可する

    app/Providers/AppServiceProvider.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/app/Providers/AppServiceProvider.php
    +++ b/app/Providers/AppServiceProvider.php
    @@ -2,6 +2,9 @@
     
     namespace App\Providers;
     
    +use App\Enums\Role;
    +use App\Models\User;
    +use Illuminate\Support\Facades\Gate;
     use Illuminate\Support\ServiceProvider;
     
     class AppServiceProvider extends ServiceProvider
    @@ -19,6 +22,9 @@ public function register(): void
          */
         public function boot(): void
         {
    -        //
    +        // 管理者はすべての操作を許可する。true 以外(null)を返すと、通常どおり Policy の判定に進む
    +        Gate::before(function (User $user, string $ability): ?bool {
    +            return $user->role === Role::Admin ? true : null;
    +        });
         }
     }

    Gate::before は、すべての権限チェックの前に呼ばれる処理です。true を返すとその時点で許可、null を返すと通常の Policy の判定に進みます。ここで false を返すと、Policy に関係なくすべて拒否になってしまうので注意してください。

    📰 出典:Laravel 12.x Authorization(Intercepting Gate Checks)

    コントローラーと FormRequest で認可をかける

    FormRequest の authorize()

    前回「第3回で Policy に置き換える」としていた authorize() を、Policy を呼ぶ形に変えます。false を返すと、入力チェックより前に 403 になります。

    app/Http/Requests/StoreCustomerRequest.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/app/Http/Requests/StoreCustomerRequest.php
    +++ b/app/Http/Requests/StoreCustomerRequest.php
    @@ -14,11 +14,11 @@
     class StoreCustomerRequest extends FormRequest
     {
         /**
    -     * 誰がこの操作をしてよいか。第2回はログイン済みなら許可し、第3回で Policy に置き換える。
    +     * 誰がこの操作をしてよいか。CustomerPolicy::create() で判定し、false なら 403 を返す。
          */
         public function authorize(): bool
         {
    -        return $this->user() !== null;
    +        return $this->user()?->can('create', Customer::class) ?? false;
         }
     
         /**

    app/Http/Requests/UpdateCustomerRequest.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/app/Http/Requests/UpdateCustomerRequest.php
    +++ b/app/Http/Requests/UpdateCustomerRequest.php
    @@ -14,6 +14,14 @@
      */
     class UpdateCustomerRequest extends StoreCustomerRequest
     {
    +    public function authorize(): bool
    +    {
    +        /** @var Customer $customer */
    +        $customer = $this->route('customer');
    +
    +        return $this->user()?->can('update', $customer) ?? false;
    +    }
    +
         public function rules(): array
         {
             /** @var Customer $customer */

    コントローラーの Gate::authorize()

    FormRequest を使わないメソッド(一覧・登録画面の表示・編集画面の表示・削除)では、Gate::authorize() で判定します。許可されなければ、その場で 403 の例外が発生して処理が止まります。

    app/Http/Controllers/CustomerController.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/app/Http/Controllers/CustomerController.php
    +++ b/app/Http/Controllers/CustomerController.php
    @@ -10,17 +10,30 @@
     use App\Http\Requests\UpdateCustomerRequest;
     use App\Models\Customer;
     use Illuminate\Http\RedirectResponse;
    +use Illuminate\Http\Request;
    +use Illuminate\Support\Facades\Gate;
     use Inertia\Inertia;
     use Inertia\Response;
     
     class CustomerController extends Controller
     {
    -    public function index(): Response
    +    public function index(Request $request): Response
         {
    +        Gate::authorize('viewAny', Customer::class);
    +
    +        $user = $request->user();
             $customers = Customer::query()
                 ->select(['id', 'code', 'name', 'email', 'phone', 'updated_at'])
                 ->orderByDesc('id')
    -            ->paginate(20);
    +            ->paginate(20)
    +            // 行ごとに「編集・削除できるか」を添えて渡す(ボタンの表示制御用。判定の本体はサーバー側)
    +            ->through(fn (Customer $customer): array => [
    +                ...$customer->toArray(),
    +                'can' => [
    +                    'update' => $user->can('update', $customer),
    +                    'delete' => $user->can('delete', $customer),
    +                ],
    +            ]);
     
             return Inertia::render('customers/Index', [
                 'customers' => $customers,
    @@ -29,6 +42,8 @@ public function index(): Response
     
         public function create(): Response
         {
    +        Gate::authorize('create', Customer::class);
    +
             return Inertia::render('customers/Create');
         }
     
    @@ -42,6 +57,8 @@ public function store(StoreCustomerRequest $request): RedirectResponse
     
         public function edit(Customer $customer): Response
         {
    +        Gate::authorize('update', $customer);
    +
             return Inertia::render('customers/Edit', [
                 'customer' => $customer->only(['id', 'code', 'name', 'name_kana', 'email', 'phone', 'note']),
             ]);
    @@ -56,6 +73,8 @@ public function update(UpdateCustomerRequest $request, Customer $customer): Redi
     
         public function destroy(Customer $customer): RedirectResponse
         {
    +        Gate::authorize('delete', $customer);
    +
             $customer->delete();
     
             return to_route('customers.index')->with('success', '顧客を削除しました。');

    create() にも Gate::authorize('create', Customer::class) を入れています。Laravel 12 の新しいプロジェクトでは、基底の Controller クラスに $this->authorize() 用の仕組みが入っていないため、Gate ファサードを使っています。

    一覧では、through() で各行に can.update と can.delete を付けて画面に渡しています。行ごとに Policy を呼んでいるので、将来ルールが「担当顧客だけ」に変わっても、画面側のコードは変えずに済みます。

    権限を Vue に渡してボタンを出し分ける

    共有プロップに「登録できるか」を追加

    「新規登録」ボタンは特定の行に属さないので、すべての画面に渡す共有プロップ(第2回で完了メッセージを追加した場所)に入れます。

    app/Http/Middleware/HandleInertiaRequests.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/app/Http/Middleware/HandleInertiaRequests.php
    +++ b/app/Http/Middleware/HandleInertiaRequests.php
    @@ -2,6 +2,7 @@
     
     namespace App\Http\Middleware;
     
    +use App\Models\Customer;
     use Illuminate\Foundation\Inspiring;
     use Illuminate\Http\Request;
     use Inertia\Middleware;
    @@ -45,6 +46,10 @@ public function share(Request $request): array
                 'quote' => ['message' => trim($message), 'author' => trim($author)],
                 'auth' => [
                     'user' => $request->user(),
    +                // 画面のボタン表示に使う権限(Policy の判定結果をそのまま渡す)
    +                'can' => [
    +                    'createCustomer' => $request->user()?->can('create', Customer::class) ?? false,
    +                ],
                 ],
                 'ziggy' => [
                     ...(new Ziggy)->toArray(),

    一覧画面でボタンを出し分ける

    resources/js/pages/customers/Index.vue に次の変更を加えます(+ が追加、- が削除)。

    --- a/resources/js/pages/customers/Index.vue
    +++ b/resources/js/pages/customers/Index.vue
    @@ -3,18 +3,18 @@
     import Heading from '@/components/Heading.vue';
     import { Button } from '@/components/ui/button';
     import AppLayout from '@/layouts/AppLayout.vue';
    -import { type BreadcrumbItem, type Customer, type Paginated, type SharedData } from '@/types';
    +import { type BreadcrumbItem, type CustomerRow, type Paginated, type SharedData } from '@/types';
     import { Head, Link, router, usePage } from '@inertiajs/vue3';
     
     defineProps<{
    -    customers: Paginated<Customer>;
    +    customers: Paginated<CustomerRow>;
     }>();
     
     const page = usePage<SharedData>();
     
     const breadcrumbs: BreadcrumbItem[] = [{ title: '顧客', href: '/customers' }];
     
    -const destroy = (customer: Customer) => {
    +const destroy = (customer: CustomerRow) => {
         if (!confirm(`「${customer.name}」を削除します。よろしいですか?`)) {
             return;
         }
    @@ -29,7 +29,7 @@ const destroy = (customer: Customer) => {
             <div class="space-y-4 p-4">
                 <div class="flex items-center justify-between">
                     <Heading title="顧客一覧" :description="`全 ${customers.total} 件`" />
    -                <Button as-child>
    +                <Button v-if="page.props.auth.can.createCustomer" as-child>
                         <Link :href="route('customers.create')">新規登録</Link>
                     </Button>
                 </div>
    @@ -55,10 +55,10 @@ const destroy = (customer: Customer) => {
                             <td class="py-2">{{ customer.email }}</td>
                             <td class="py-2">{{ customer.phone }}</td>
                             <td class="space-x-2 py-2 text-right">
    -                            <Button variant="outline" size="sm" as-child>
    +                            <Button v-if="customer.can.update" variant="outline" size="sm" as-child>
                                     <Link :href="route('customers.edit', customer.id)">編集</Link>
                                 </Button>
    -                            <Button variant="destructive" size="sm" @click="destroy(customer)">削除</Button>
    +                            <Button v-if="customer.can.delete" variant="destructive" size="sm" @click="destroy(customer)">削除</Button>
                             </td>
                         </tr>
                         <tr v-if="customers.data.length === 0">

    TypeScript の型には、Auth に can: { createCustomer: boolean }、User に role、一覧の行に can: { update: boolean; delete: boolean } を持つ CustomerRow を追加します。resources/js/types/index.d.ts に次の変更を加えます(+ が追加、- が削除)。

    --- a/resources/js/types/index.d.ts
    +++ b/resources/js/types/index.d.ts
    @@ -4,6 +4,9 @@ import type { Config } from 'ziggy-js';
     
     export interface Auth {
         user: User;
    +    can: {
    +        createCustomer: boolean;
    +    };
     }
     
     export interface BreadcrumbItem {
    @@ -33,6 +36,7 @@ export interface User {
         email: string;
         avatar?: string;
         email_verified_at: string | null;
    +    role: 'admin' | 'staff' | 'viewer';
         created_at: string;
         updated_at: string;
     }
    @@ -69,3 +73,8 @@ export interface Customer {
         note: string | null;
         updated_at?: string;
     }
    +
    +// 一覧の各行に付く権限(CustomerController::index で付与)
    +export interface CustomerRow extends Customer {
    +    can: { update: boolean; delete: boolean };
    +}

    Feature テストで 403 を確かめる

    権限のテストで大切なのは、「画面にボタンが無いこと」ではなく「URL を直接たたいても拒否されること」を確かめることです。

    tests/Feature/CustomerPolicyTest.php を新しく作ります。

    tests/Feature/CustomerPolicyTest.php の全文(118行)
    <?php
    
    // tests/Feature/CustomerPolicyTest.php
    
    declare(strict_types=1);
    
    namespace Tests\Feature;
    
    use App\Enums\Role;
    use App\Models\Customer;
    use App\Models\User;
    use Illuminate\Foundation\Testing\RefreshDatabase;
    use Inertia\Testing\AssertableInertia as Assert;
    use Tests\TestCase;
    
    class CustomerPolicyTest extends TestCase
    {
        use RefreshDatabase;
    
        private const VALID_INPUT = ['code' => 'C00001', 'name' => '株式会社サンプル'];
    
        public function test_viewer_can_see_the_list_but_without_edit_buttons(): void
        {
            Customer::factory()->create();
    
            $this->actingAs(User::factory()->viewer()->create())
                ->get('/customers')
                ->assertOk()
                ->assertInertia(fn (Assert $page) => $page
                    ->component('customers/Index')
                    ->where('auth.can.createCustomer', false)
                    ->where('customers.data.0.can.update', false)
                    ->where('customers.data.0.can.delete', false)
                );
        }
    
        public function test_viewer_cannot_create_update_or_delete(): void
        {
            $viewer = User::factory()->viewer()->create();
            $customer = Customer::factory()->create();
    
            // 画面にボタンが無くても、URL を直接たたけば届く。サーバー側で 403 を返すことを確かめる
            $this->actingAs($viewer)->get('/customers/create')->assertForbidden();
            $this->actingAs($viewer)->post('/customers', self::VALID_INPUT)->assertForbidden();
            $this->actingAs($viewer)->get("/customers/{$customer->id}/edit")->assertForbidden();
            $this->actingAs($viewer)->put("/customers/{$customer->id}", self::VALID_INPUT)->assertForbidden();
            $this->actingAs($viewer)->delete("/customers/{$customer->id}")->assertForbidden();
    
            $this->assertDatabaseCount('customers', 1);
            $this->assertDatabaseMissing('customers', ['code' => 'C00001']);
        }
    
        public function test_staff_can_create_and_update_but_not_delete(): void
        {
            $staff = User::factory()->create(); // 既定は担当者
            $this->assertSame(Role::Staff, $staff->role);
    
            $this->actingAs($staff)->post('/customers', self::VALID_INPUT)->assertRedirect('/customers');
            $customer = Customer::where('code', 'C00001')->firstOrFail();
    
            $this->actingAs($staff)
                ->put("/customers/{$customer->id}", ['code' => 'C00001', 'name' => '変更後'])
                ->assertRedirect('/customers');
    
            $this->actingAs($staff)->delete("/customers/{$customer->id}")->assertForbidden();
            $this->assertModelExists($customer);
    
            $this->actingAs($staff)
                ->get('/customers')
                ->assertInertia(fn (Assert $page) => $page
                    ->where('auth.can.createCustomer', true)
                    ->where('customers.data.0.can.update', true)
                    ->where('customers.data.0.can.delete', false)
                );
        }
    
        public function test_admin_can_do_everything(): void
        {
            $admin = User::factory()->admin()->create();
            $customer = Customer::factory()->create();
    
            $this->actingAs($admin)
                ->get('/customers')
                ->assertInertia(fn (Assert $page) => $page
                    ->where('auth.can.createCustomer', true)
                    ->where('customers.data.0.can.delete', true)
                );
    
            $this->actingAs($admin)->delete("/customers/{$customer->id}")->assertRedirect('/customers');
            $this->assertModelMissing($customer);
        }
    
        public function test_new_users_are_viewers_by_default(): void
        {
            $this->post('/register', [
                'name' => '新規ユーザー',
                'email' => 'new@example.com',
                'password' => 'password',
                'password_confirmation' => 'password',
            ]);
    
            $this->assertSame(Role::Viewer, User::where('email', 'new@example.com')->firstOrFail()->role);
        }
    
        public function test_role_cannot_be_changed_from_the_profile_form(): void
        {
            $viewer = User::factory()->viewer()->create();
    
            // プロフィール更新に role を混ぜて送っても、$fillable に無いので保存されない
            $this->actingAs($viewer)->patch('/settings/profile', [
                'name' => $viewer->name,
                'email' => $viewer->email,
                'role' => 'admin',
            ]);
    
            $this->assertSame(Role::Viewer, $viewer->fresh()->role);
        }
    }

    このテストでは、閲覧のみのユーザーでは一覧の auth.can.createCustomer と各行の can がすべて false になること、担当者は登録・編集できるが削除は 403 になること、管理者はすべてできること、会員登録したユーザーの既定が閲覧のみであることの、合計6件を書きました。

    テスト用のユーザーを作る UserFactory には、admin()・viewer() の状態(state)を追加し、既定は担当者にします。database/factories/UserFactory.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/database/factories/UserFactory.php
    +++ b/database/factories/UserFactory.php
    @@ -2,6 +2,7 @@
     
     namespace Database\Factories;
     
    +use App\Enums\Role;
     use Illuminate\Database\Eloquent\Factories\Factory;
     use Illuminate\Support\Facades\Hash;
     use Illuminate\Support\Str;
    @@ -29,9 +30,20 @@ public function definition(): array
                 'email_verified_at' => now(),
                 'password' => static::$password ??= Hash::make('password'),
                 'remember_token' => Str::random(10),
    +            'role' => Role::Staff,
             ];
         }
     
    +    public function admin(): static
    +    {
    +        return $this->state(fn (array $attributes) => ['role' => Role::Admin]);
    +    }
    +
    +    public function viewer(): static
    +    {
    +        return $this->state(fn (array $attributes) => ['role' => Role::Viewer]);
    +    }
    +
         /**
          * Indicate that the model's email address should be unverified.
          */

    削除は管理者だけになったので、第2回の削除のテストは管理者で実行するように直します。tests/Feature/CustomerTest.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/tests/Feature/CustomerTest.php
    +++ b/tests/Feature/CustomerTest.php
    @@ -112,7 +112,8 @@ public function test_customer_can_be_deleted(): void
         {
             $customer = Customer::factory()->create();
     
    -        $this->actingAs(User::factory()->create())
    +        // 削除は管理者のみ(第3回)
    +        $this->actingAs(User::factory()->admin()->create())
                 ->delete("/customers/{$customer->id}")
                 ->assertRedirect('/customers');
     

    画面で確かめるため、シーダーでロールの違う3人を作ります。database/seeders/DatabaseSeeder.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/database/seeders/DatabaseSeeder.php
    +++ b/database/seeders/DatabaseSeeder.php
    @@ -16,10 +16,13 @@ public function run(): void
         {
             // User::factory(10)->create();
     
    -        User::factory()->create([
    +        // ログイン確認用(パスワードはすべて password。ローカル専用)
    +        User::factory()->admin()->create([
                 'name' => 'Test User',
                 'email' => 'test@example.com',
             ]);
    +        User::factory()->create(['name' => '担当者', 'email' => 'staff@example.com']);
    +        User::factory()->viewer()->create(['name' => '閲覧者', 'email' => 'viewer@example.com']);
     
             // 一覧の確認用に、顧客を10件作る
             Customer::factory(10)->create();

    動作確認の方法

    docker compose run --rm --no-deps app php artisan test --filter=CustomerPolicyTest
    docker compose run --rm --no-deps app php artisan test
    docker compose up -d mysql app
    docker compose exec app php artisan migrate:fresh --seed   # DB を作り直してシーダーを流す(ローカル専用)

    シーダーで、管理者(test@example.com)・担当者(staff@example.com)・閲覧のみ(viewer@example.com)の3人を作ります。パスワードはいずれもローカル専用の password です。

    ロールを変えて挙動を確かめるときは、tinker(=Laravel の対話型の実行環境)を使います。

    docker compose exec app php artisan tinker --execute="App\Models\User::where('email','viewer@example.com')->update(['role'=>'staff']);"

    筆者の環境では、次のことを確認しました。

    • CustomerPolicyTest の6件を含め、全42件のテストが成功(npm run build も成功)
    • 閲覧のみでログインすると、一覧に「新規登録」「編集」「削除」のボタンが出ず、POST /customers と編集画面は 403
    • tinker で担当者に変えると「新規登録」「編集」が表示されて登録でき、削除は 403 のまま
    • 管理者でログインすると削除ボタンが表示され、削除できる

    つまずきやすい点・セキュリティ上の注意

    • ボタンを隠しただけで安心しない:画面の表示制御は、開発者ツールや直接のリクエストで簡単に回避できます。403 のテストを必ず書きましょう。
    • Gate::before で false を返さない:管理者以外に false を返すと、Policy の判定がすべて無視されて全員が拒否されます。「判定しない」は null です。
    • 会員登録を誰でもできる状態に注意:スターターキットには誰でも使える会員登録画面があります。今回は登録直後のロールを閲覧のみにしましたが、社内向けの管理画面では、本番では会員登録の画面自体を閉じ、管理者がユーザーを作る運用にするのが一般的です。連載ではロールの変更はシーダーと tinker で行い、ユーザー管理画面は作りません。
    • 権限の変更はログインし直さなくても即時に効く:ロールは毎回のリクエストでデータベースから読み直すため、変更は次の操作から反映されます。逆に、画面を開いたままだとボタンの表示は古いままなので、押した時点でサーバーが 403 を返す作りにしておくことが大切です。

    発注者向けメモ:権限表を先に決めると工数が読みやすい

    権限まわりは、「画面を作ってから考える」と手戻りが最も大きくなる部分です。発注の前に、今回のような権限表(誰が・何に・何をできるか)を作っておくと、開発会社も工数を見積もりやすくなります。

    工数が増えやすいのは、次のような条件です。

    • データ単位の権限:「自分の部署の顧客だけ見られる」「担当者本人だけ編集できる」など、ロールだけでなくデータの持ち主で判定する場合
    • 項目単位の権限:「単価は管理者にしか見せない」など、同じ画面の中で一部の項目だけを隠す場合
    • 承認フロー:「担当者が登録し、上長が承認して確定」のように、状態によってできる操作が変わる場合
    • ユーザー管理画面・操作ログ:誰がいつ権限を変えたか、誰が何を削除したかを記録する場合

    開発会社には、次のように確認してみてください。

    • 「権限のチェックは画面の表示だけでなく、サーバー側でも行いますか?そのテストはありますか?」
    • 「新しく作ったユーザーの初期の権限は何になりますか?」
    • 「ユーザーの追加や権限の変更は、誰がどの画面で行いますか?その操作は記録されますか?」
    • 「将来『担当顧客だけ編集可』のようなルールを追加する場合、どのくらい作り直しが必要ですか?」

    まとめと次回予告

    第3回では、ロールと Policy で「誰が何をできるか」を実装しました。

    • ロールは enum(admin / staff / viewer)で定義し、既定は最も弱い viewer。role は $fillable に入れない
    • 判定は CustomerPolicy に集約し、管理者は Gate::before で一括許可(判定しないときは null)
    • コントローラーは Gate::authorize()、FormRequest は authorize() で Policy を呼び、許可されなければ 403
    • Vue には判定結果(true / false)だけを渡してボタンを出し分け、テストでは「URL を直接たたいて 403」を確かめる

    次回は「案件管理と一覧画面の作り込み:検索・並べ替え・ページング」です。顧客にひもづく案件(projects)を追加し、N+1 問題の対策、検索条件の入力チェック、並べ替えとページ送り、Inertia 2 の部分リロードを使った一覧画面を作ります。

    この連載の記事一覧

    この記事は連載「Laravel+Vue.jsで作る管理画面をECSで動かす」の1回です。連載のほかの回は次のとおりです(連載の一覧ページ)。

    システム制作・運用・保守のお問い合わせはこちら

      お問い合わせ


      よかったらシェアしてね!
      • URLをコピーしました!
      • URLをコピーしました!

      この記事を書いた人

      株式会社THIRD HERO代表取締役 朝野貴朗
      Webシステム開発を中心に、toC向けサービスサイトの運営、ツール開発などを行ってまいりました。

      コメント

      コメント一覧 (2件)

      目次