我试图重定向到上一页的消息时,有一个致命的错误。
App::fatal(function($exception)
{
return Redirect::back()->with('msg', 'The Message');
}
在视图中尝试访问msg
Sessions::get('msg')
但是什么都没有渲染,是我做错了吗?
我试图重定向到上一页的消息时,有一个致命的错误。
App::fatal(function($exception)
{
return Redirect::back()->with('msg', 'The Message');
}
在视图中尝试访问msg
Sessions::get('msg')
但是什么都没有渲染,是我做错了吗?
当前回答
在控制器
例如
return redirect('login')->with('message',$message);
刀片锉 消息将存储在会话中而不是变量中。
例如
@if(session('message'))
{{ session('message') }}
@endif
其他回答
我自己不再为laravel写这篇文章,而是支持为您处理这一切的Laracasts包。它真的很容易使用,并保持您的代码干净。甚至还有一个laracast来说明如何使用它。你所要做的就是:
通过Composer导入包。
"require": {
"laracasts/flash": "~1.0"
}
在app/config/app.php中包含服务提供者。
'providers' => [
'Laracasts\Flash\FlashServiceProvider'
];
在底部的同一个文件中添加一个facade别名:
'aliases' => [
'Flash' => 'Laracasts\Flash\Flash'
];
将HTML拖到视图中:
@include('flash::message')
在消息的右侧有一个关闭按钮。这依赖于jQuery,所以请确保在引导之前添加它。
可选的变化:
如果你不使用bootstrap或者想要跳过flash消息的包含并自己编写代码:
@if (Session::has('flash_notification.message'))
<div class="{{ Session::get('flash_notification.level') }}">
{{ Session::get('flash_notification.message') }}
</div>
@endif
如果你想查看@include('flash::message')拉进来的HTML,你可以在vendor/laracasts/flash/src/views/message.blade.php中找到它。
如果你需要修改部分做:
php artisan view:publish laracasts/flash
这两个包视图现在将位于' app/views/packages/laracasts/flash/'目录中。
在Laravel 5.4中,以下内容对我有用:
return back()->withErrors(['field_name' => ['Your custom message here.']]);
我知道这是一个老帖子,但这个答案可能会帮助到一些人。
在Laravel 8。这对我来说是有效的:你可以将错误返回到上一页或另一页。
return Redirect::back()->withErrors(['password' => ['Invalid Username or Password']]);
这也可以:
return view('auth.login')->withErrors(['username' => ['Invalid Username or Password']]);
但是,请确保您返回的页面/视图具有与withErrors方法中传递的第一个参数(在本例中是用户名或密码)对应的字段名,并且视图中的@error指令像这样引用相同的字段
@error('password') //or @error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
例如
希望这能帮助到一些人。欢呼。
**Try This**
Try This Code
--- Controller ---
return redirect('list')->with('message', 'Successfully');
return redirect('list');
---- Blade view ------
@if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
@endif
Try
return Redirect::back()->withErrors(['msg' => 'The Message']);
在视图中调用这个
@if($errors->any())
<h4>{{$errors->first()}}</h4>
@endif