Laravelを使ったWebアプリを作成中、管理者機能を作る必要があり、簡易的に機能を作ったので備忘録として残しておきます。筆者は、Laravel初学者なのでかなり強引に作っているかと思います。その点はご了承ください。
(本当は、Laravel Permissionなどを使ったほうがいいと思います)
環境
・Laravel 10.48.20
・PHP 8.2.21
・Breeze
経緯
特定の機能は管理者のみに表示したいので、管理者機能を作りたい。
初期データで管理者を入れ、ほかの新規登録ユーザーは自動的に一般ユーザーにしたい。
具体的なコード
users_table
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
//追加
$table->boolean('administrator');
$table->timestamps();
});
}
User.php
protected $fillable = [
'name',
'email',
'password',
//追加
'administrator',
];
RegisteredUserController.php
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|lowercase|email|max:255|unique:'.User::class,
'password' => ['required', 'confirmed', Rules\Password::defaults()],
//追加
'administrator' => 'nullable',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
//追加
'administrator' => 0,
]);
これで新規登録を行った際にそのユーザーを勝手に一般ユーザー(administrator === 0)として登録してくれます。管理人はシーディングファイルでこの値を1にしています。
Viewで管理人だけに見せたい表示があれば、if文を使えば表示できます。
blade.php
@if(Auth::check() === true)
@if(Auth::user()->administrator === 1)
//この間に処理を記載
@endif
@endif
その他
管理人だけがアクセスできるページを作るならこちらの記事が参考になるかと思います。
https://qiita.com/3ur0/items/40ba156ae42ceab5a830
参考記事
https://kinsta.com/jp/blog/laravel-breeze/
https://tech-tech.blog/php/laravel/laravel-breeze/