[英]Laravel custom redirection after validation errors
如果登錄過程中出現任何類型的錯誤,我可以問我在我的 LoginRequest.php 中做錯了什么,我在其中設置了重定向到自定義登錄頁面的條件嗎? 我的代碼如下:
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class LoginRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'login_email' => 'required',
'login_password' => 'required'
];
}
public function messages()
{
return [
'login_email.required' => 'Email cannot be blank',
'login_password.required' => 'Password cannot be blank'
];
}
public function redirect()
{
return redirect()->route('login');
}
}
如果有任何錯誤,代碼應該將從導航欄登錄表單登錄的用戶重定向到主登錄頁面,但它似乎沒有重定向。
如果你想重定向到一個特定的 url,那么使用protected $redirect
class LoginRequest extends Request
{
protected $redirect = "/login#form1";
// ...
}
或者如果你想重定向到一個命名路由,那么使用$redirectRoute
class LoginRequest extends Request
{
protected $redirectRoute = "session.login";
// ...
}
找到了解決辦法。 我需要做的就是覆蓋來自
表單請求.php
像這樣,它就像一個魅力。
public function response(array $errors)
{
// Optionally, send a custom response on authorize failure
// (default is to just redirect to initial page with errors)
//
// Can return a response, a view, a redirect, or whatever else
if ($this->ajax() || $this->wantsJson())
{
return new JsonResponse($errors, 422);
}
return $this->redirector->to('login')
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
如果您不想在請求上使用 validate 方法,您可以使用 Validator Facade 手動創建一個驗證器實例。 Facade 上的 make 方法生成一個新的驗證器實例:參考Laravel 驗證
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
如果您在Controller
上使用validate()
方法
$this->validate($request, $rules);
然后您可以從您擴展的基本Controller
上存在的ValidatesRequests
特征覆蓋buildFailedValidationResponse
。
沿着這條線的東西:
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->expectsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->route('login');
}
這適用於 Lara 7 添加一個錨點以在驗證失敗時跳轉到評論表單
protected function getRedirectUrl()
{
return parent::getRedirectUrl() . '#comment-form';
}
已經提供了對此答案的變體,但是在自定義請求中覆蓋getRedirectUrl()
方法可以使您能夠定義路由參數,而不僅僅是$redirectRoute
屬性提供的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.