search
HomeBackend DevelopmentPHP Tutorial[Laravel 5 Fundamentals] 20 – Flash Message

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');    } 

当文章创建成功后,页面会 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');    } 

至此,还不能显示,只是在 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>   

在原先的 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> 

做了两个动作,第一,在下面引入两个 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> 

首先,在

这里对 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 

而就一句的意思就是说,如果有重要的 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]);     }               

这样也是ok的。

总结

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

Statement
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.