Giter Site home page Giter Site logo

laravel-flash's Introduction

A lightweight package to flash messages

Latest Version on Packagist run-tests Total Downloads

This is a lightweight package to send flash messages in Laravel apps. A flash message is a message that is carried over to the next request by storing it in the session. This package only supports one single flash message at a time.

This is how it can be used:

class MySpecialSnowflakeController
{
    public function store()
    {
        // …

        flash('My message', 'my-class');

        return back();
    }
}

In your view you can do this:

@if (flash()->message)
    <div class="{{ flash()->class }}">
        {{ flash()->message }}
    </div>
@endif

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-flash

Usage

Here is an example on how to flash a message.

class MyController
{
    public function store()
    {
        // …

        flash('My message');

        return back();
    }
}

In your view you can use it like this

@if(flash()->message)
    <div>
        {{ flash()->message }}
    </div>
@endif

Using a class name to style the displayed message

You can add a class as the second parameter. This is typically used to style the output in your HTML.

class MyController
{
    public function store()
    {
        // …

        flash('My message', 'my-class');

        return back();
    }
}

In your view you can use the class like this:

@if (flash()->message)
    <div class="{{ flash()->class }}">
        {{ flash()->message }}
    </div>
@endif

You can also set an array of classes. These will be output by flash()->class by imploding the array with a space-delimiter.

flash('My message', ['my-class', 'another-class']); // flash()->class output is: 'my-class another-class'

Adding your own methods

If you don't want to specify a class each time you flash a message you can add a method name to flash.

The easiest way is by passing an array to the levels method. The key is the method name that should be added to flash(). The value is the class that will automatically be used when rendering the message.

// this would probably go in a service provider

\Spatie\Flash\Flash::levels([
    'success' => 'alert-success',
    'warning' => 'alert-warning',
    'error' => 'alert-error',
]);

The above example will make these methods available on flash:

flash()->success('Hurray');
flash()->warning('Mayybeee');
flash()->error('Oh Oh');

The most likely scenario is that you want to consume the flash message in a view. You can use the message, class and level properties on the view.

@if (flash()->message)
    <div class="{{ flash()->class }}">
        {{ flash()->message }}
    </div>

    @if(flash()->level === 'error')
        This was an error.
    @endif
@endif

Additionally, when you've added your own method, you can also pass that method name as a second parameter to flash itself:

flash('Hurray', 'success'); // `flash()->class` will output 'alert-success'

You can also add a method to flash by using macro.

Here's an example:

// this would probably go in a service provider

use Spatie\Flash\Message;

\Spatie\Flash\Flash::macro('warning', function (string $message) {
    return $this->flashMessage(new Message($message, 'alert alert-warning'));
});

You can now use a warning method on flash:

flash()->warning('Look above you!');

You can pass the desired level as the third argument to Message.

// in a service provider
use Spatie\Flash\Message;

\Spatie\Flash\Flash::macro('warning', function (string $message) {
    return $this->flashMessage(new Message($message, 'alert alert-warning', 'my-level'));
});

// in the next request, after having flashed a message 
flash()->level; // returns `my-level`

Alternatives

This package is intended to be lightweight. If you need things like multiple messages, support for Bootstrap, overlays, ... take a look at this excellent flash package by Jeffrey Way or Laraflash by Ilya Sakovich.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-flash's People

Contributors

adrianmrn avatar alexvanderbist avatar benjamincrozat avatar brendt avatar davimug avatar drbyte avatar faustbrian avatar freekmurze avatar jrmajor avatar laravel-shift avatar patinthehat avatar paulredmond avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-flash's Issues

Is there a way you may show the flash message once?

Is there a way you may show the flash message once?

I mean, for first you are in the contact route, you submit the contact form and a redirect to a success route is done. So in this success route a "flash" alert appears, then you press a link to other route and finally you press browser's back button and the flash is triggered again. Is there a way to avoid this behavior?

Greetings!

mutli request together

hi
consider you have multiple browser tab. and you have form on each tab. then you click submit button of all form in all tabs very fastly (submit all form in each browser tab together).
then when we redirect to back() the flash message only shows in one browser tab and doesnt show on other tabs.

Support for PHP 7.3

Hello,

Release note of v1.4.0 is "drop support for PHP 7.3"

I was wondering why this package would drop support for PHP 7.3 this early.
Or was it just a typo I hope? 😅

502 when using macro methods to flash messages

This https://github.com/spatie/laravel-flash/blob/master/src/Flash.php#L54 seems to cause a circular method call which results in a 502 status code when using methods like flash()->success() which have been created via macros.

    public function flash(Message $message): void
    {
        if ($message->class && static::hasMacro($message->class)) {
            $methodName = $message->class;

            // this calls back to the macro which in turn calls this `flash` method again
            $this->$methodName($message->message);

            return;
        }

        $this->session->flash('laravel_flash_message', $message->toArray());
    }

    public static function levels(array $methodClasses): void
    {
        foreach ($methodClasses as $method => $classes) {
            self::macro($method, function (string $message) use ($classes) {
               // this calls the flash method which will call the macro method again which means we end up here again with circular calls 
               // return $this->flash(new Message($message, $classes));

                // those changes solve the circular calls
                $message = new Message($message, $classes);

                // now the message gets flashed
                $this->session->flash('laravel_flash_message', $message->toArray());
            });
        }
    }

Will try to take a look the next days when I find time.

Carry flash messages across redirect

In my codebase I have the following code:

public function destroy(DeleteResourceRequest $request, string $resource_uuid)
{
     // delete resource...

     flash()->success('Resource was deleted');

     return redirect('admin/resources');
}

However, after the redirect, the flash message has disappeared. Is there a way to carry the message over the redirect?

Followed docs but getting error

I've installed the package via composer.

Then all I've done is add

flash('My message');

into my function. Here is the entire function

public function sms(Request $request)
    {

        $message = $request->email." -- ".$request->phone." -- ".$request->message;

        $sms = new SendText();
        $sms->sendsms("+xxxxxxxxxxx", $message);

        flash('My message');

        return back();
    }

I'm getting the following error:

Symfony\Component\Debug\Exception\FatalThrowableError
syntax error, unexpected 'Session' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

Screenshot 2020-05-20 at 22 29 28

Use HTML in flash message?

Is there any way to pass a link within the flash message? When I pass HTML, such as flash('Registration failed. Please <a href="#">contact admin</a>'));, the HTML is shown verbatim.

Dependency injection

Hey! Thanks for this lightweight package, I've enjoyed using it on a few projects. Quick question: is there a way to use dependency injection for creating flash messages instead of the global flash() helper?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.