kazweda / laravel-crud

0 stars 0 forks source link

更新機能 #8

Closed kazweda closed 1 day ago

kazweda commented 1 day ago

【Laravel】CRUD機能を作成する③更新機能(Update)

kazweda commented 1 day ago

編集画面表示とデータ更新

@section('title', 'ユーザー一覧')

@section('content')

ユーザー一覧

<!-- ユーザー登録ページへのリンク -->
<a href="{{ route('users.create') }}"
    class="mb-4 inline-block bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
    ユーザー登録
</a>

       <!-- セッションメッセージ -->
        @if (session('message'))
            <div><strong>{{ session('message') }}</strong></div>
        @endif

<div class="overflow-x-auto">
    <table class="min-w-full divide-y divide-gray-200">
        <thead>
            <tr>
                <th class="px-6 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                <th class="px-6 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider">名前</th>
                <th class="px-6 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
            @foreach ($users as $user)
                <tr>
                    <td class="px-6 py-4 whitespace-nowrap">{{ $user->id }}</td>
                    <td class="px-6 py-4 whitespace-nowrap"><a href="{{ route('users.show', $user->id) }}"
                            class="text-blue-500 hover:underline">{{ $user->name }}</a></td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <a href="{{ route('users.edit', $user->id) }}"
                            class="text-indigo-600 hover:text-indigo-900">編集</a>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
</div>

@endsection

kazweda commented 1 day ago
sail artisan make:view users/edit

@section('title', 'ユーザー情報編集')

@section('content')

@csrf @method('PUT')

ユーザー情報編集(変更する箇所のみ入力してください)

@error('name')
{{ $message }}
@enderror
@error('email')
{{ $message }}
@enderror
@error('password')
{{ $message }}
@enderror
@if (session('message'))
{{ session('message') }}
@endif @if (session('user'))

登録したユーザーの情報

名前: {{ session('user')->name }}

メールアドレス: {{ session('user')->email }}

@if (session('passwordChanged'))

パスワード: ********

@endif
@endif

@endsection

kazweda commented 1 day ago

ルート設定

use Illuminate\Support\Facades\Route; use App\Http\Controllers\UsersController;

Route::prefix('users')->group(function () { Route::get('/', [UsersController::class, 'index'])->name('index'); Route::get('/create', [UsersController::class, 'create'])->name('create'); Route::post('/store', [UsersController::class, 'store'])->name('store'); Route::get('/{user}', [UsersController::class, 'show'])->name('show'); Route::get('/{user}/edit', [UsersController::class, 'edit'])->name('edit'); Route::put('/{user}', [UsersController::class, 'update'])->name('update'); });

kazweda commented 1 day ago

更新時のバリデーション

sail artisan make:request UpdateUserRequest
kazweda commented 1 day ago

Screenshot 2024-09-20 at 3 05 16 PM

kazweda commented 1 day ago

UsersController.php

    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        return view('users.show', compact('user'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(User $user)
    {
        return view('users.edit', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateUserRequest $request, User $user)
    {
        $data = $request->validated();

        $passwordChanged = false; // パスワードが変更されたかどうかのフラグ

        // パスワードが入力されている場合のみ更新
        if (!empty($data['password'])) {
            $passwordChanged = true;
        } else {
            unset($data['password']); // パスワードフィールドをデータ配列から削除
        }

        DB::beginTransaction();

        try {
            $user->update($data);

            DB::commit();

            return
                redirect()->route('users.edit', $user->id)->with(compact('user', 'passwordChanged'));;
        } catch (\Exception $e) {
            DB::rollback();

            return back()->with(['message' => '更新中にエラーが発生しました。' . $e->getMessage()]);
        }
    }