向laravel中的控制器发布表单操作

时间:2019-09-12 21:19:20

标签: laravel forms action

首先,我想说我的问题与此question非常相似,只是在我的情况下答案无济于事。

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

enter image description here

在我的个人资料/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>

UsersController

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');

这是我收到的错误

enter image description here

非常感谢您!

2 个答案:

答案 0 :(得分:2)

更改这些路线:

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>

答案 1 :(得分:1)

您可以尝试执行以下操作:

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

并以如下形式使用它:

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