我的问题是我的POST请求总是在错误302 之后重定向到GET
这是我的路线文件:
Route::auth();
...
Route::post('/personnalite/creer', 'PersonnaliteController@creerPost')->name('personnaliteCreerPost');
Route::get('/personnalite/creer', 'PersonnaliteController@creerGet')->name('personnaliteCreerGet');
...
当我在发布前删除get路由时,laravel路由失败。我可以在我的网络浏览器开发工具中看到重定向前的帖子请求
这是我的middelware,它在"web"middelwareGroups中注册。它只是检查用户角色是否允许路由(ACL规则在配置文件中注册)
class MyAclMiddleware {
public function handle($request, Closure $next) {
$myAcl = App::offsetExists('MyAcl') ? App::make('MyAcl') : null;
if($myAcl) {
if(Auth::guest()) {
$myAcl->setRole(0);
} else {
$myAcl->setRole(Auth::user()->role);
}
if($myAcl->isNotAllowed('route.' . Route::getRoutes()->match($request)->getName())) {
return redirect()->route('erreur', ['id' => 0]);
}
}
return $next($request);
}
}
这是我的表单刀片模板:
@extends('layouts.app')
@section('content')
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Créer une personnalité politique</div>
<div class="panel-body">
{{ @Form::open(['route' => 'personnaliteCreerPost', 'files' => true]) }}
@include('personnalite.subviews.formInfosGenerales')
{{ Form::submit('Créer') }}
{{ @Form::close() }}
@include('personnalite.subviews.listePersonnalites')
</div>
</div>
</div>
</div>
@enduction
其他开箱即用的laravel表单和用于登录的控制器。。。工作良好。
有人能帮我解决这个问题吗?
已解决!
问题是由于我的控制器中的表单验证逻辑不正确(测试不足=>没有表单验证=>重定向到以前的表单)
我真丢脸
302重定向是Laravel(非ajax)的默认验证失败。你可以通过这样做来控制它:
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
]);
if ($validator->fails()) {
$errors = $validator->errors();
return redirect()->back()->withErrors($errors)->withInput();
}
通过捕获故障,然后手动重定向,您可以确定返回到页面的内容。此外,这些错误不会显示在您的页面上,除非您有一些代码来显示它们——它们保存在会话变量中。因此,看起来你只是在以某种奇怪的循环路线返回页面,而实际上却显示了错误。复数,withErrors,适用于一系列验证错误,可以显示在刀片模板的适当字段下,如下所示:
@if ($errors->has('first_name'))
<span class="text-danger">{!! $errors->first('first_name') !!}</span>
@endif
然后你在页面的顶部有这样的东西:
@if (session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
@if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
哪些捕获从您的控制器发送的自定义错误消息,如:
return redirect()->back()->withSuccess('Profile updated');
或
return redirect()->back()->with("error","New Password does not match the password confirmation field. Please make sure they are the same.");
请注意"errors"answers"error"之间只有一个字母的区别。如果你打错了字,可能会绊倒你。
为了完成,状态422是通过对控制器的ajax调用从验证失败中返回的。拉拉威尔为你做了那么多!
这可能对其他用户有用,因为他们有同样的问题,无法用上面的解决方案解决:
确保例如<input type="text" name="document_name">
(document_name)的表单字段名称与模型中声明的规则字段的名称匹配public static $rules = ['document_name' => 'required|string'];
它没有抛出任何错误,日志中没有任何错误,它只是重定向到表单,因此很难找到问题。
对我来说,这就是问题所在,与你的原因"糟糕的表单验证逻辑"不谋而合。