在发生致命错误时,我正在尝试带有消息地重定向回上一页。
App::fatal(function($exception)
{
return Redirect::back()->with('msg', 'The Message');
}
在尝试访问消息时
Sessions::get('msg')
但是什么都没有被渲染出来,我在这里做错了什么吗?
请试试
return Redirect::back()->withErrors(['msg' => 'The Message']);
在您的视图内调用此函数:
@if($errors->any())
<h4>{{$errors->first()}}</h4>
@endif
`return Redirect::back()->with('msg', 'The Message');`
如何在这里获取 "msg" 呢? - M TSession::has('msg')
,'msg' 并不存在。 - M TSession::put()
。 - giannis christofakiswithErrors('some error')
需要将错误信息作为字符串而不是数组传递。 - sentyLaravel 5及以上版本
控制器(Controller)
return redirect()->back()->with('success', 'your message,here');
刀锋:
@if (\Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{!! \Session::get('success') !!}</li>
</ul>
</div>
@endif
return redirect()->back()->with('message', '数量约束失败');
在重定向的位置的blade文件中,我添加了以下代码:@if(session()->has('message'))
{{session('message')}}
@endif
- Rajib另一种方法是
控制器
use Session;
Session::flash('message', "Special message goes here");
return Redirect::back();
查看
@if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
@endif
在 Laravel 5.4 中,以下方法适用于我:
return back()->withErrors(['field_name' => ['Your custom message here.']]);
withErrors()
方法的参数是一个包含两个元素的数组:['msg','The Message']
。请参阅API以获取可接受的参数:https://laravel.com/api/4.2/Illuminate/Http/RedirectResponse.html#method_withErrors - haakymwithErrors()
方法的参数是一个包含了一个key => value
对的数组,其中value是一个数组。5.4的API文档:https://laravel.com/api/5.4/Illuminate/Http/RedirectResponse.html#method_withErrors - haakym你有一个错误(拼写错误):
Sessions::get('msg')// an extra 's' on end
Session::get('msg')
我认为现在它应该可以工作了,对于我来说确实如此。
只需在您的控制器函数中设置闪存消息并重定向回到上一页。
session()->flash('msg', 'Successfully done the operation.');
return redirect()->back();
然后你可以在视图 blade 文件中获取消息。
{!! Session::has('msg') ? Session::get("msg") : '' !!}
{!! Session::get("msg", '') !!}
就足够了。get()
已经检查了 key 是否存在,如果不存在则返回默认值。 - Emile Bergeron在 Laravel 5.5 中:
return back()->withErrors($arrayWithErrors);
在使用Blade模板时的视图中:@if($errors->has())
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
对于 Laravel 5.5+:
控制器:
return redirect()->back()->with('success', 'your message here');
刀片:
@if (Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{{ Session::get('success') }}</li>
</ul>
</div>
@endif
return redirect()->back()->withErrors(['name' => 'The name is required']);
在 Blade 模板引擎中:
@error('name')
<p>{{ $message }}</p>
@enderror
return Redirect::back()->withErrors(['password' => ['Invalid Username or Password']]);
这种方法同样有效:
return view('auth.login')->withErrors(['username' => ['Invalid Username or Password']]);
@error('password') //or @error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
s
,并在需要的地方添加use
。除此之外 - 应该可以工作。 - Yevgeniy Afanasyev