Laravel跳转到之前页面,并带着错误信息back()->withErrors([‘错了’])是什么问题?
之前使用 Laravel 5.1 开发项目时,经常会遇到需要携带错误信息到上一页的情况,尤其是在开发网页后台的时候。
方法一:跳转到有错误信息的指定路由
return redirect(‘/admin/resource/showAddResourceView/’ . $customer_id)
->withErrors([‘此授权码已过期,请重新生成!’]);
方法二:跳转到上个页面,并携带错误信息
return back()->withErrors([‘此激活码已与该用户绑定过!’]);
方法三:validate验证(这种情况应该是最多的)
我们在提交表单的时候,进入控制器的步就是验证输入的参数符不符合我们的要求,如果不符合,就直接带着输入、错误信息返回到上一个页面,这个是框架自动完成的。具体例子:
$rules = [
‘user_name’ => ‘unique:customer|min:4|max:255’,
’email’ => ’email|min:5|max:64|required_without:user_name’,
‘customer_type’ => ‘required|integer’,
];
$messages = [
‘user_name.unique’ => ‘用户名已存在!’,
‘user_name.max’ => ‘用户名长度应小于255个字符!’,
’email.required_without’ => ‘邮箱或者用户名必须至少填写一个!’,
‘customer_type.required’ => ‘用户类型必填!’,
];
$this->validate($request, $rules, $messages);
然后在视图里面引入公共的错误信息:
D:\phpStudy\WWW\xxx\resources\views\admin\error.blade.php
<div class=”form-group”>
@if (count($errors) > 0)
<div class=”alert alert-danger”>
<ul style=”color:red;”>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
</div>
例如:
@extends(‘admin.master’)
@section(‘css’)
@parent
<link href=”{{%20asset(‘css/plugins/iCheck/custom.css’)%20}}” rel=”external nofollow” rel=”stylesheet”>
@endsection
@section(‘content’)
{{– {{dd($data)}} –}}
<div class=”wrapper wrapper-content animated fadeInRight”>
@include(‘admin.error’)
如果还需要自定义错误信息,并且把之前传过来的值返回到上一个视图,还需要加个withInput;
if (empty($res)) {
return back()->withErrors([‘查不到这个用户,请检查!’])->withInput();
}
实际显示效果如下:
withErrors([‘错了’])是什么问题?” fetchpriority=”high” decoding=”async” class=”alignnone size-full wp-image-4807″ src=”https://shuyeidc.com/wp/wp-content/uploads/2025/02/20250217183500-67b381546a061.jpg” alt=”” width=”873″ height=”1024″ />
文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/115449.html<