Closed kazweda closed 1 day ago
@extends('layouts.app')
@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
sail artisan make:view users/edit
@extends('layouts.app')
@section('title', 'ユーザー情報編集')
@section('content')
@endsection
<?php
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'); });
sail artisan make:request UpdateUserRequest
/**
* 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()]);
}
}
【Laravel】CRUD機能を作成する③更新機能(Update)