在Laravel 5中闪烁反馈消息

I want to flash feedback messages like "An entry has been created successfully" or "You don't have enough permissions to access this item".

I want to avoid embedding these messages straight into views, because they can re-appear, for example, when a user navigates back to the previous page with his browser.

To solve this problem, I have a javascript function that acts like following:

(showFlashMessage(){
    // 1. make an ajax request
    // 2. retrieve a flash message (if any)
    // 3. display the message
})();

This way, the problem of the reappearance of the flash messages is solved. However, by the time the request is made, the flash message has already disappeared. How should I solve this problem?

If you want to solve the problem on the server side you can make use of the Session facade like so:

In your controller:

function create() {
    if(Gate::allows('createAccess')) {
        Session::flash('error', 'You don't have enough permissions to access this item!');

        return redirect()->back();
    }

    // Create the model or perform any other logic

    Session::flash('success', 'An entity has been created successfully!');

    return view('entities.show');
}

Then you can have a partial named message.blade.php which is included in your entities.show view:

@if (Session::has('message'))
    <div class="alert alert-info">
        <p>{{ Session::get('message') }}</p>
    </div>
@endif

If you want to solve the problem on the client side you can call your message function (for example sweet alert message) in the success callback when the request has been completed successfully:

function showMessage() {
    $.ajax({
        url: 'your-url',
        data: {
            // Your data here
        },
        success: function() {
            // Show success message
        },
        error: function() {
            // Show error message
        }
    });
}

I would suggest keeping it simple and call the inbuilt flash() method in your controller:

flash()->error('We encountered an error whilst doing something');
return redirect('path') //action(), back(), etc;

By my understanding, Laravel handles these flash messages in the session and they persist only for the next page view before being removed. If you want to reuse a specific message or combination of message type and content, consider storing this in either a DB table or in helper.php

Another option is to pull in the Laracasts/Flash/Flash package