Table of Contents
Flash Message
添加 flash message
展示 flash message
消失 flash message
叉掉 flash message
自动消失 flash message
另一种添加 flash message 的方式
总结
Home Backend Development PHP Tutorial [Laravel 5 Fundamentals] 20 – Flash Message

[Laravel 5 Fundamentals] 20 – Flash Message

Jun 23, 2016 pm 01:08 PM

Flash Message

前言

上一节,我们对 Laravel 前端的 assets 一个了解,Laravel 的前端管理利器: elixir + gulp 。本节回到 php 方面,对 flash message 的使用做一个讲解。

说明

开发环境:Windows 7

Laravel 版本: 5+

IDE: Phpstorm

什么是 flash message , flash , 闪烁,稍纵即逝,message ,消息。大概其直译就是“闪信”,其原先是出自 rails 的,用于在页面上显示一些提示信息。在 Laravel 里引入这个概念,对页面上需要的信息做一个提示。

当用户在你的网站上做了什么行为之后,你要对其行为做一个响应回复。比如注册了,那你得提示“注册成功”,不是 js alert() 的效果,但是 alert() 的用意。

在我们的博客系统中或许就可以用到。党我们新创建完一篇文章之后,就会立马跳转至文章列表页面,比较突兀。来一个提示多好,提示我创建完成——虽然我知道创建完成了。

添加 flash message

首先,打开 ArticlesController.php ,找到 store() 方法,我们实现存储写好的文章的方法就在此。代码如下:

public function store(ArticleRequest $request)    {        $article = new Article($request->all());        Auth::user()->articles()->save($article);        return redirect('articles');    } 
Copy after login

当文章创建成功后,页面会 redirect 到 /articles ,此时,我们可以在 session 中创建一个 flash message 的对象,包装在一个 k-v 中:

public function store(ArticleRequest $request)    {        $article = new Article($request->all());        Auth::user()->articles()->save($article);        \Session::flash('flash_message','Your article has been created!');        return redirect('articles');    } 
Copy after login

至此,还不能显示,只是在 session 中加入了一个键值对,想显示那就得根据 k 来提取 v 。这里的 session 之所以有一个 flash() 方法,是因为 Laravel 框架里面写好了,你也可以写一个 Session::put ,这个和 flash 的区别就在于,flash是“一锤子买卖”,一个请求一个 flash message ,当你 reload 页面,该 flash message 就消失了,但是 put 不同。

展示 flash message

我们来到我们的 master.blade.php 中,这里定义了我们所有布局文件的格式。我们在这里添加如下代码:

<divclass="container">                                                                @if (Session::has('flash_message'))                                                    <divclass="alert alert-success">                                                          {{Session::get('flash_message')}}                                          </div>      @endif    @yield('content')                                                              </div>                                                                              <divclass="footer">                                                                    @yield('footer')                                                                </div>   
Copy after login

在原先的 content 上面加一个逻辑语句,来判断 session 对象中是不是有一个名为 ‘flash_message’ 的 key , 有的话提取出来显示在 content 上面。

至此,我们的 flash message j就可以显示了。启动服务器,访问 localhost:8888/articles/create 登陆后,发表文章,然后你会看到顶上的绿色提示。当你 reload 该页面,提示消失。 flash ~

消失 flash message

没错,每次 reload 页面,这是什么坑爹做法? 怎么办? 那就给它添加一个叉号,或者定时消失。

叉掉 flash message

先看叉号。

在刚才的 blade 里面添加这么一句:

<divclass="container">                                                                @if (Session::has('flash_message'))                                                    <divclass="alert alert-success">                                                          <buttontype="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>                {{Session::get('flash_message')}}                                          </div>      @endif    @yield('content')                                                              </div>                <scriptsrc="//code.jquery.com/jquery.js"></script>                        <scriptsrc="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <divclass="footer">                                                                    @yield('footer')</div> 
Copy after login

做了两个动作,第一,在下面引入两个 js 文件,第二在上面添加一段 button 控件的代码,意思也很明朗。

再去浏览器访问 localhost:8888/articles/create ,创建完成后,可以看到有一个小叉在提示的右上角,而且点击后消失,免去了 reload 页面。

自动消失 flash message

下面一种逻辑,提示分为两种,一种是重要的,一种是不重要的,不重要的让它自己按时间消失,重要的让用户去点叉。

好的,下面看一下怎么实现:

<divclass="container">    @if (Session::has('flash_message'))        <divclass="alert alert-success {{ Session::has('flash_message_important') ? 'alert-important':''}}">                @if (Session::has('flash_message_important'))                        <buttontype="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>                @endif                {{Session::get('flash_message')}}        </div>    @endif    @yield('content') </div><scriptsrc="//code.jquery.com/jquery.js"></script><scriptsrc="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script><script>        $('div.alert').not('.alert-important').delay(3000).slideUp(300);</script> <divclass="footer">    @yield('footer') </div> 
Copy after login

首先,在

这里对 session 中的 key 做一个判断,如果有一个名为 flash messageimportant 的 key ,则给 div 继续添加一个 alert-important 的类属性,否则不添加。

@if (Session::has('flash_message_important'))                        <buttontype="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>@endif 
Copy after login

而就一句的意思就是说,如果有重要的 flash_message ,那么就显示一个叉号。

最后还添加了一段 jquery 的 js , 用来 div 的自动消失。逻辑是若果不是重要消息,那么展示3s后,自动消失。

各位可以在 localhost:8888/articles/create 中创建完之后看看效果。

如果想看点叉的效果的话,回到 ArticlesController.php,在\Seesion下面添加一句

\Session::flash(‘flash messageimportant’,true); 保存再创建文章试试看~

另一种添加 flash message 的方式

添加 session 还有一种方法。打开 ArticlesControler.php ,添加如下代码:

public function store(ArticleRequest $request)                                      {                                                                                      $article = new Article($request->all());                                            Auth::user()->articles()->save($article);                                           //\Session::flash('flash_message','Your article has been created!');                //\Session::flash('flash_message_important',true);         return redirect('articles')->with([                                                    'flash_message'=>'Your article has been created!',                                  'flash_message_important'=>true]);     }               
Copy after login

这样也是ok的。

总结

flash mesage 作为提示方式在 web 设计中起着人性化的一面,给用户的选择更多,更贴心,交互感更好。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles