Tự học Laravel: (23) FLASH MESSAGE

Last time we implemented article deletion. After I deleted the article, I redirected to the article list, but I didn’t see any message, and it was hard to tell if the article was deleted correctly. This time, we will implement a flash message to inform the user that the article has been successfully deleted.

CONTROLLER

Modify the destroy method of ArticlesController.php.

// app/Http/Controllers/ArticlesController.php
...
 
class ArticlesController extends Controller
{
    ...
    public function destroy($id) {
        $article = Article::findOrFail($id);
 
        $article->delete();
 
        return redirect('articles')->with('message', 'Delete Article Successful');
    }
}

Add a message as flush information in the with() method at redirect() time.
Flash information is temporary session information (information stored on the server) that is valid only for the next request.

VIEW

Modify layout.blade.php to display a flash message.

// resources/views/layout.blade.php 
...
<body>
    <div class="container py-4">
        @if (session('message'))
            <div class="alert alert-success">{{ session('message') }}</div>
        @endif

        @yield('content')
    </div>
</body>
</html>

Modified to display if the session has information with ‘message’ as key. class=”alert alert-success” is Bootstrap’s CSS. If you specify this class, div will be displayed in green as a normal alert.

EXERCISE

Let’s fix it so that flash messages are displayed in the store and update methods of ArticlesController.php.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.