I'm making my first app in Laravel and am trying to get my head around the session flash messages. As far as I'm aware in my controller action I can set a flash message either by going

Redirect::to('users/login')->with('message', 'Thanks for registering!'); //is this actually OK?

对于重定向到另一条路由的情况,或者

Session::flash('message', 'This is a message!'); 

在我的主Blade 模板中,我有:

@if(Session::has('message'))
<p class="alert alert-info">{{ Session::get('message') }}</p>
@endif

As you may have noticed I'm using Bootstrap 3 in my app and would like to make use of the different message classes: alert-info, alert-warning, alert-danger etc.

Assuming that in my controller I know what type of message I'm setting, what's the best way to pass and display it in the view? Should I set a separate message in the session for each type (e.g. Session::flash('message_danger', 'This is a nasty message! Something's wrong.');)? Then I'd need a separate if statement for each message in my blade template.

Any advice appreciated.

推荐答案

One solution would be to flash two variables into the session:

  1. The message itself
  2. alert 的"级别"

例如:

Session::flash('message', 'This is a message!'); 
Session::flash('alert-class', 'alert-danger'); 

那么在你看来:

@if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>
@endif

Note I've put a default value into the Session::get(). that way you only need to override it if the warning should be something other than the alert-info class.

(that is a quick example, and untested :) )

Laravel相关问答推荐

Laravel FAKER语法

Laravel:在 PHPUnit 的覆盖率报告中包含文件夹(如果在 app/ 文件夹之外)?

spatie 包 laravel-tags 在迁移中没有 down() 函数是有原因的吗

FileViewFinder.php 第 137 行中的 Laravel 5 InvalidArgumentException:未找到视图 [.admin]

如何通过一个 laravel 安装处理子域

在 laravel 中动态更改时区

Laravel 4:如何将 WHERE 条件应用于 Eloquent 类的所有查询?

Laravel 5表单请求验证返回禁止错误

Guzzle - Laravel如何使用 x-www-form-url-encoded 发出请求

我的composer 不会完全用 Laravel 4 更新它会被artisan卡住

使用 Eloquent 的 Laravel 块方法

Laravel 5 如何全局设置 Cache-Control HTTP 标头?

使用 Laravel 和 Passport 验证失败时响应状态码 401?

Laravel 5 make:控制器在应用程序文件夹而不是控制器文件夹中创建控制器

向 Docker 上的 Artisan 推荐方式

Laravel Eloquent:计算总价的最佳方法

Laravel 5 环境配置数组?

Laravel 4:将什么作为参数传递给 Url 类?

如何在 Eloquent Orm 中实现自引用(parent_id)模型

如何在没有日志(log)、没有信息的情况下调试 Laravel 错误 500