zaichaopan/flash

A simple package to make flash message more flexible

v0.1-beta 2018-06-21 23:09 UTC

This package is not auto-updated.

Last update: 2024-04-21 03:30:36 UTC


README

This package makes Laravel flash message more flexible. It can be used in laravel 5.5 or higher.

Installation

composer require zaichaopan/flash

Usage

In laravel, you can flash message like below

$request->session()->flash($key, $message);

Or you can use the with method when redirect

// in your controller action method
return redirect()->with($key, $message);

// or take advantage of dynamically binding
return redirect()->withSuccess($message); // or withError, withWarning, ...

But the problem is when it comes to showing flash message in blade, your flash message may have different keys (e.g. error, success, ...). You have to check all the possible keys to determine if you have flash message to show in the blade. This package can be used to make things easier.

  • To flash a message

This packages provides a global helper method flash to create a Flash instance. After you create the Flash instance, there are five available methods you can call to generate five different types of flash messages. Each method takes two parameters: message and options.

The first one is required which is used to set the message body of the flash. The second one is an array and it is optional. It is used to add addition data to the flash.

// generate a general info message
flash()->info($message, $options) ;

// generate a success message
flash()->success($message, $options);

// generate a warning message
flash()->warning($message, $options);

// generate a danger message
flash()->danger($message, $options);

// generate an error message
flash()->error($message, $options);
  • Check whether flash exists:
<!-- your blade -->
@if (flash()->ready())
<!-- your flash html -->
@endif
  • Get flash type:
flash()->type();
  • Get flash message
flash()->message();
  • Get additional option data
flash()->options();
  • Pass data to javascript

In real life, you may want to create a flash component in vue, which can be used to display the flash message from the server or from the js. To do that, let's say you have a component called Flash.vue and there is a property called flash inside it.

<Flash :flash={{ json_encode(flash()) }}></Flash>

Now if there is no flash, the value of the flash property will be null. If there is a flash message, the value will be an object contains properties: message, type, options.