How to Display Alerts in Laravel (Default)

Posted on

Alerts are crucial for providing feedback to users after they perform actions such as form submissions, data updates, or deletions in your Laravel application. In this guide, we will walk through how to display alerts in Laravel application (success or error) and make them disappear automatically after a few seconds.

How to Display Alerts in Laravel (Default)
Laravel update success

Step 1: Setting Flash Messages in the Controller

First, let’s set up our controller to handle flash messages. We will use session flash messages to store the success or error messages. Here’s an example of updating user data and setting flash messages accordingly:

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

public function updateUser(Request $request, $id)
{
    $dataBaru = $request->all();

    try {
        // Update data in the database
        DB::table('users')->where("id", $id)->update($dataBaru);

        // Set flash message for success
        session()->flash('success', 'Data updated successfully!');
    } catch (\Exception $e) {
        // Set flash message for error
        session()->flash('error', 'Failed to update data: ' . $e->getMessage());
    }

    // Redirect back
    return back();
}

Step 2: Displaying Flash Messages in the Blade View

Next, we need to display these flash messages in our Blade view. We will add conditional statements to check for the presence of success or error messages and display them accordingly.

@if (session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif

@if (session('error'))
    <div class="alert alert-danger">
        {{ session('error') }}
    </div>
@endif

Step 3: Making Alerts Disappear Automatically

To enhance user experience, we can make these alerts disappear automatically after a few seconds using JavaScript. Here are two methods: one using jQuery and another using plain JavaScript.

Using jQuery

  1. Add jQuery to your view if it’s not already included.
  2. Add a script to set a timeout for the alert elements.
<!DOCTYPE html>
<html>
<head>
    <!-- Add jQuery if not already included -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    @if (session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    @if (session('error'))
        <div class="alert alert-danger">
            {{ session('error') }}
        </div>
    @endif

    <script>
        // Hide alert after 3 seconds
        $(document).ready(function(){
            setTimeout(function(){
                $(".alert").fadeOut("slow", function(){
                    $(this).remove();
                });
            }, 3000);
        });
    </script>
</body>
</html>

Using Plain JavaScript

  1. Add a script to set a timeout for the alert elements.
<!DOCTYPE html>
<html>
<head>
    <!-- No jQuery required -->
</head>
<body>
    @if (session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    @if (session('error'))
        <div class="alert alert-danger">
            {{ session('error') }}
        </div>
    @endif

    <script>
        // Hide alert after 3 seconds
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(function() {
                var alerts = document.querySelectorAll('.alert');
                alerts.forEach(function(alert) {
                    alert.style.transition = 'opacity 0.5s ease';
                    alert.style.opacity = '0';
                    setTimeout(function() {
                        alert.remove();
                    }, 500); // Additional time for transition
                });
            }, 3000);
        });
    </script>
</body>
</html>

With these steps, you can effectively display success and error alerts in your Laravel application, and ensure they automatically disappear after a few seconds, providing a smooth and user-friendly experience.