Laravel Filamentを使用した管理画面構築の巻(3)下

Date:

Share post:

前回Breezeをインストールしたことにより、ユーザー用の認証ができているところまでの状態になっているかと思いますので確認してみます。前々回の時に作成したfilamentのユーザーでログインしてみます。

filamentのログインは問題ないと思います。次にフロント側でログインしてみます。

どちらでもできてしまいますね・・・。

これは管理ユーザー側の認証情報だけが使用されている状況ですので、当初に申し上げました

  • 一般ユーザー:一般ログイン
  • 管理者ユーザー:管理者ログイン

ができるように実装していく必要があります。それではやっていきましょう。

まず現状のDBのテーブルの状態を確認してみます。

アカウントを管理しているテーブルは「users」になります。

管理者ユーザーと一般ユーザーを分けて管理するために、Modelとmigrationファイルを作成して管理者テーブル(モデル名:Admin)を追加しようと思います。

php artisan make:model -m

Modelとmigrationファイルができたら修正していきます。

******** app/Models/Admin.php ********

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * 更新可能な属性
     *
     * @var array<string, string> $fillable
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * シリアライズのため、非表示にしておく属性
     *
     * @var array<string, string> $hidden
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * キャストする属性
     *
     * @var array<string, string> $casts
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

}
******** database/migrations/2024_06_17_023213_create_admins_table.php ********

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('admins');
    }
};

Modelとmigrationファイルが修正できたら、認証の guards と providers に今回追加した管理ユーザー用の設定を追加していきます。場所は

config/auth.php になります。

******** config/auth.php ********

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option defines the default authentication "guard" and password
    | reset "broker" for your application. You may change these values
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => env('AUTH_GUARD', 'web'),
        'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | which utilizes session storage plus the Eloquent user provider.
    |
    | All authentication guards have a user provider, which defines how the
    | users are actually retrieved out of your database or other storage
    | system used by the application. Typically, Eloquent is utilized.
    |
    | Supported: "session"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication guards have a user provider, which defines how the
    | users are actually retrieved out of your database or other storage
    | system used by the application. Typically, Eloquent is utilized.
    |
    | If you have multiple user tables or models you may configure multiple
    | providers to represent the model / table. These providers may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => env('AUTH_MODEL', App\Models\User::class),
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => env('AUTH_MODEL', App\Models\Admin::class),
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | These configuration options specify the behavior of Laravel's password
    | reset functionality, including the table utilized for token storage
    | and the user provider that is invoked to actually retrieve users.
    |
    | The expiry time is the number of minutes that each reset token will be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    | The throttle setting is the number of seconds a user must wait before
    | generating more password reset tokens. This prevents the user from
    | quickly generating a very large amount of password reset tokens.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | window expires and users are asked to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),

];

最後に、filamentの管理画面の認証を行う guard を新しく作成したadminに指定します。

filamentの管理画面が使用する AdminPanelProvider.php が以下のディレクトリに存在しますので、そこに追記します。

app/Providers/Filament/AdminPanelProvider.php

******** app/Providers/Filament/AdminPanelProvider.php ********

<?php

namespace App\Providers\Filament;

use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Pages;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\Widgets;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\AuthenticateSession;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;

class AdminPanelProvider extends PanelProvider
{
    public function panel(Panel $panel): Panel
    {
        return $panel
            ->default()
            ->id('admin')
            ->path('admin')
            ->login()
            ->colors([
                'primary' => Color::Amber,
            ])
            ->discoverResources(in: app_path('Filament/Resources'), for: 'App\\Filament\\Resources')
            ->discoverPages(in: app_path('Filament/Pages'), for: 'App\\Filament\\Pages')
            ->pages([
                Pages\Dashboard::class,
            ])
            ->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\\Filament\\Widgets')
            ->widgets([
                Widgets\AccountWidget::class,
                Widgets\FilamentInfoWidget::class,
            ])
            ->middleware([
                EncryptCookies::class,
                AddQueuedCookiesToResponse::class,
                StartSession::class,
                AuthenticateSession::class,
                ShareErrorsFromSession::class,
                VerifyCsrfToken::class,
                SubstituteBindings::class,
                DisableBladeIconComponents::class,
                DispatchServingFilamentEvent::class,
            ])
            ->authMiddleware([
                Authenticate::class,
            ])
            ->authGuard('admin');
    }
}

ソースの追加、修正が完了しましたので、管理者テーブルを追加します。

$ php artisan migrate

migrate できたのでテーブルの状態を確認してみます。

adminsテーブルができていますね。

続けて動作状態を確認してみます。当初管理画面用ユーザーとして作成したアカウントでfilamentにログインしてみます。

もともとあったusersテーブルはユーザー管理用となりましたので、元々作成したアカウントではログインできなくなることが確認できました。ただしフロント画面の方はログインできています。

では新たにfilamentの管理ユーザーを作成してみます。

作成したユーザーでfilamentにログインします。

ログインできましたね!ユーザーログインと管理者ログインを分けることができました。

今回4回に渡りfilamentの基本的(ヘルプドキュメントを見るとまだいろいろ機能がありそう・・・)な環境構築について書いてきましたが、比較的簡単な手順で導入することが可能ですので、自分も何かの機会があれば使っていきたいと思った次第です。

Related articles

Laravel Filamentを使用した管理画面...

前回、filamentでのリソース作成...

Laravel Filamentを使用した管理画面...

前回、Filamentをインストールし...

Laravel Filamentを使用した管理画面...

以前触ったことがあるLarav...

LaravelでPDF生成(mpdf)

EC関連のシステムなどでは請求書や領...