[英]Routing correctly in Laravel
我正在學習 Laravel 5.7.15。
我正在嘗試更新 Laravel 中的數據。 當我更新客戶端評論時,我收到 MethodNotAllowedHttpException。
我已經查看了與此錯誤相關的其他帖子,但現在仍將其修復,請幫助我。
Laravel 讓我發瘋。
這是我的 html
{!! Form::open(['url' => '/client_report/'.$id.'/edit', 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
{{ csrf_field() }}
<div class="form-group">
{{Form::text("Comment",$client->client_comments, array('id'=>'comment' 'class' => 'form-control', 'disabled' => 'disabled', 'placeholder'=>'Client Comments')) }}
<p>{{Form::submit('Submit',['class'=>'btn btn-space btn-success'}}</p>
</div>
和路線有
Route::get('/client_report/{id}/{edit}',function($id) {
return view('clientEdit')
->with('id',$id);
})->middleware('auth');
Route::post('/client/submit/{id}/edit', ['uses' => 'clientController@editClient']);
和控制器有
class clientController extends Controller {
function editClient(Request $request, $id) {
$client = Client::find($id);
$client->comment = $request->get('comment');
$client->save();
}
}
任何幫助將不勝感激。
我認為你在這里傳遞的網址是錯誤的。
{!! Form::open(['url' => '/client_report/'.$id.'/edit', 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
上述方法用於編輯,當您點擊提交按鈕時,它應該重定向到/client/submit/{id}/edit
這個 url。
讓你形成如下網址。
{!! Form::open(['url' => '/client/submit/'.$id.'/edit', 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
01.首先將你的路由器方法改為PUT
Route::put('/client/submit/update/{id}', ['uses' => 'clientController@editClient']);
02.改變你的形式
{!! Form::open(['action' => ['clientController@editClient', $id ],'method' => 'POST', 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
{{Form::text("Comment",$client->client_comments, array('id'=>'comment' 'class' => 'form-control', 'disabled' => 'disabled', 'placeholder'=>'Client Comments')) }}
{{ Form::hidden('_method', 'PUT')}}
{{ Form::submit('submit', [ 'class' => 'btn btn-primary m-t-15 m-b-15'])}}
{!! Form::close() !!}
你打錯了網址。
在您使用的 html 中
Form::open(['url' => '/client_report/'.$id.'/edit' ...
但你的更新路線是
Route::post('/client/submit/{id}/edit' ...
更改表單中的 URL,同時確保發出POST請求而不是GET 。
根據restful約定,更新資源應該有PUT/PATCH路由。
PS:當前的laravel 版本是7.x,我建議你至少學習laravel 6.x,並且不推薦使用來自Collectives 的HTML(據我記得這就是它們的名字)。 你不應該使用過時的技術。
將路線改為:
Route::match(['put', 'patch'], '/client/submit/{id}', 'clientController@editClient');
和表格:
{!! Form::open(['url' => '/client_report/'.$id, 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
{{ csrf_field() }}
@method('PUT')
...
https://laravel.com/docs/master/routing#form-method-spoofing
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.