0
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?

2. ユーザー管理の基本

Last updated at Posted at 2025-02-08

2.1 ユーザーモデルの理解

ユーザーモデルの確認

app/Models/User.php

<?php

namespace App\Models;

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

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];
}

2.2 ユーザーテーブルの作成

マイグレーションの確認

database/migrations/xxxx_xx_xx_xxxxxx_create_users_table.php

public function up()
{
    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->timestamps();
    });
}

マイグレーションの実行

php artisan migrate

2.3 ユーザー登録・更新・削除

ユーザー登録

use App\Models\User;

User::create([
    'name' => 'Test User',
    'email' => 'test@example.com',
    'password' => bcrypt('password123'),
]);

ユーザーの取得

$user = User::find(1);

ユーザーの更新

$user->update(['name' => 'Updated Name']);

ユーザーの削除

$user->delete();

2.4 認証の導入

Laravel Breezeの導入

composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate

ルートにアクセス

  • http://127.0.0.1:8000/login
  • http://127.0.0.1:8000/register

2.5 認証のカスタマイズ

ログインユーザー情報の取得

use Illuminate\Support\Facades\Auth;

$user = Auth::user();

認証ミドルウェアの使用

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('auth');

2.6 役割(Roles)と権限(Permissions)の管理

Spatieの導入

composer require spatie/laravel-permission
php artisan migrate

ロールと権限の追加

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

$role = Role::create(['name' => 'admin']);
$permission = Permission::create(['name' => 'edit articles']);

$role->givePermissionTo($permission);

ユーザーにロールを付与

$user->assignRole('admin');

認可の使用(Blade)

@can('edit articles')
    <button>記事を編集</button>
@endcan

2.7 まとめ

  • ユーザーモデルとデータベースの操作 を理解。
  • Laravel Breezeを使った認証の実装
  • ミドルウェアで認証済みユーザーのみアクセス可能にする
  • Spatieを使ったロールと権限の管理

次のステップでは、パスワードリセット・メール認証・API認証(Sanctum) について学ぼう!

0
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
0
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?