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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles