post 在 laravel 中形成对控制器的操作

post form action to controller in laravel

首先我想说的是我的问题和这个很相似,只是这个答案不适合我。

我正在尝试将我的表单操作连接到我的 UserController。这是一个更新头像功能。这是它的样子。

在我的 profile/show.blade

<div class="col-md-12 justify-content-center">
    <form action="{{ action('UsersController@update_avatar') }}" method="post" enctype="multipart/form-data">
        @csrf

    </form>
</div>

用户控制器

public function avatar()
{
    $user = Auth::User();
    return view('dashboard.profile'.$user->id,compact('user',$user));
}

public function update_avatar(Request $request){

    $request->validate([
        'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    $user = Auth::User();

    $folder = 'avatars';
    Storage::delete($folder.'/'.$user->avatar); 

    $avatarName = $user->id.'_avatar'.'.'.request()->avatar->getClientOriginalExtension();

    $request->avatar->storeAs('avatars',$avatarName);

    $user->avatar = $avatarName;
    $user->save();

    return back()
        ->with('success','You have successfully upload image.');
}

routes/web.php

Route::get('dashboard/profile/{{profile}}', 'Dashboard\UsersController@avatar');
Route::post('dashboard/profile/{{profile}}', 'Dashboard\UsersController@update_avatar');

这是我收到的错误

在此先感谢您!

您可以尝试这样做:

Route::post('dashboard/profile','Dashboard\UsersController@update_avatar')->name(profile.update);

并以这样的形式使用它:

<form action="{{ route('profile.update') }}">

更改这些路线:

Route::get('dashboard/profile/{{profile}}', 'Dashboard\UsersController@avatar');
Route::post('dashboard/profile/{{profile}}', 'Dashboard\UsersController@update_avatar');

致这些:

Route::get('dashboard/profile/{{profile}}', 'UsersController@avatar')->name('user.avatar');
Route::post('dashboard/profile/{{profile}}', 'UsersController@update_avatar')->name('user.update_avatar');

并且在您的表单中使用 route 而不是 action

<form action="{{ route('user.update_avatar') }}" method="post" enctype="multipart/form-data">
    @csrf
</form>