@metehod('PUT')処理がGET処理になってしまう。
Q&A
解決したいこと
@mthod('PUT')を使用ているのですが、開発者ツールで確認するとGETに変換されてしまうので、変換されないようにしたいです。
該当するソースコード
LALAVELを使用してHTMLでアプリを作成しています。
ソースコードを入力
viewsファイル
@csrf @method('PUT')routesファイル
Route::get('/profile/edit', [UserController::class, 'editProfile'])->middleware('auth')->name('profile.edit'); // プロフィール設定ページ
Route::put('/profile/update', [UserController::class, 'updateProfile'])->middleware('auth')->name('profile.update'); // プロフィール編集処理
Controllersファイル
/**
* プロフィール更新処理
*/
public function updateProfile(UpdateProfileRequest $request)
{
Log::info('updateProfile メソッドが呼び出されました。');
Log::info('HTTPメソッド: ' . $request->method());
Log::info('受け取ったリクエストデータ: ' . json_encode($request->all()));
$user = Auth::user();
$validatedData = $request->validated();
// プロフィール画像の保存
if ($request->hasFile('profile_image')) {
$validatedData['profile_image'] = $request->file('profile_image')->store('profile_images', 'public');
}
try {
// ユーザー情報更新
$user->update([
'name' => $validatedData['name'] ?? $user->name,
'email' => $validatedData['email'] ?? $user->email,
'profile_image' => $validatedData['profile_image'] ?? $user->profile_image,
]);
// `addresses` テーブルの更新
$address = Address::where('user_id', $user->id)->first();
if ($address) {
$address->update([
'postal_code' => $validatedData['postal_code'] ?? $address->postal_code,
'address' => $validatedData['address'] ?? $address->address,
'building_name' => $validatedData['building_name'] ?? $address->building_name,
]);
} else {
Address::create([
'user_id' => $user->id,
'postal_code' => $validatedData['postal_code'],
'address' => $validatedData['address'],
'building_name' => $validatedData['building_name'],
]);
}
Log::info('ユーザー情報と住所情報が正常に更新されました。');
} catch (\Exception $e) {
Log::error('情報の更新中にエラーが発生しました: ' . $e->getMessage());
return redirect()->route('profile.edit')->with('error', 'プロフィールの更新に失敗しました。');
}
Log::info('updateProfile 処理が完了しました。');
return redirect()->route('items.index')->with('success', 'プロフィールが更新されました!');
}
// ログインページのビューを返す
public function showLogin()
{
return view('auth.login');
}
このように設定しました。
自分で試したこと
nginxのdefault.confファイルに
server {
listen 80;
index index.php index.html;
server_name localhost;
root /var/www/public;
location / {
try_files $uri $uri/ /index.php$is_args$args;
# PUT, DELETE メソッドを許可の記述を追加!
limit_except GET POST PUT DELETE {
allow all;
}
}
.htaccessこのファイルに
RewriteCond %{REQUEST_METHOD} !^(GET|POST|PUT|DELETE)$
RewriteRule ^ index.php [L]
この記述を追加しました。
VerifyCsrfToken.phpこのファイルに、
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//'profile/update', // ← CSRF チェックを除外をためしました!
'profile/update'
];
}
長々と書き込んでしまい申し訳ありません。
これ以外の対処方法が思い浮かばないので知恵をおかしいただけると幸いです。
よろしくお願いいたします。