【发布时间】:2021-09-17 10:35:10
【问题描述】:
我想提交一个带有 post 请求的表单,控制器中的方法将重定向到一个视图。
控制器:
//Create quotation
public function quotation(Request $request){
$validated = $request->validate([
'parcel_weight' => 'required',
'parcel_size' => 'required',
'postcode_pickup' => 'required|postal_code:MY|exists:postcodes,postcode',
'postcode_delivery' => 'required|postal_code:MY|exists:postcodes,postcode'
]);
//logic to compute the quotation rate for each courier based on the inputs
//dd($request->all());
return redirect()->route('quotation.show');
}
//Show quotation
public function showQuotation(){
return view('orders.quotation');
}
web.php:
//Create new order
Route::get('/dashboard/orders','Dashboard\OrderController@index')->name('order.index');
//Generate quotation
Route::post('/dashboard/orders','Dashboard\OrderController@quotation')->name('order.quotation');
//Quotation page
Route::get('/dashboard/orders/quotation','Dashboard\OrderController@showQuotation')->name('quotation.show');
此代码工作正常,但要点击route('quotation.show'),必须从表单提交数据。如果我只是复制 URI 并粘贴到浏览器 .../dashboard/orders/quotation 中,那么我仍然可以在不提交任何输入的情况下查看该页面。如何防止这种情况发生?
编辑:
使用with() 似乎不起作用。
//Create quotation
public function quotation(Request $request){
$validated = $request->validate([
'parcel_weight' => 'required',
'parcel_size' => 'required',
'postcode_pickup' => 'required|postal_code:MY|exists:postcodes,postcode',
'postcode_delivery' => 'required|postal_code:MY|exists:postcodes,postcode'
]);
//logic to compute the quotation rate for each courier based on the inputs
//dd($request->all());
return redirect()->route('quotation.show')->with(['form','form']);
}
//Show quotation
public function showQuotation(){
if(request()->has('form')){
dd('Data has been submitted');
}else{
dd('NO DATA');
}
}
【问题讨论】:
-
在
redirect()->route()上使用->with(['something' => 'something']),并检查是否request()->has('something')。如果没有,请阻止该操作。 -
@TimLewis 有没有其他方法可以用辅助函数来完成这个?
-
一般来说,
GET请求应该返回一个view(),POST请求应该返回一个redirect()无论如何。如果您不想直接从插入的 URL 访问GET请求,则使用->with()从POST重定向,它设置了session变量将完成此操作,并且(据我所知)可以不容易被欺骗。 -
不知何故我尝试使用
->with(),但request()....无法检测到 -
@TimLewis 我更新了我的问题以显示代码的外观。即使我提交了表单,它仍然没有返回任何数据。