DEV Community

Jérôme W
Jérôme W

Posted on • Edited on

How to use SweetAlert2 in Laravel 8 using Composer

Alt Text

This tutorial explains how to use in your existing Laravel 8 project the popular JavaScript SweetAlert2 library, using Composer.

Please be indulgent for my first tutorial 😅
I will try to be clear and concise 😃

Installation

Following the official documentation, first thing you need to do is to use Composer to add the package to your project's dependencies :



composer require realrashid/sweet-alert


Enter fullscreen mode Exit fullscreen mode

After installing the sweet-alert package, register the service provider in your config/app.php configuration file :



'providers' => [
    /*
    * Package Service Providers...
    */
    RealRashid\SweetAlert\SweetAlertServiceProvider::class,
],


Enter fullscreen mode Exit fullscreen mode

Also, add the Alert facade to the aliases array in the same configuration file :



'aliases' => [
    (...)
    'Alert' => RealRashid\SweetAlert\Facades\Alert::class,
],


Enter fullscreen mode Exit fullscreen mode

Finaly, you must add the sweetalert view in your master layout :



@include('sweetalert::alert')


Enter fullscreen mode Exit fullscreen mode

And run the below command to publish the package assets :



php artisan sweetalert:publish


Enter fullscreen mode Exit fullscreen mode

Use

To use SweetAlert2 globally in your project, you must add a middleware in your base controller app/Http/Controllers/Controller.php :



use RealRashid\SweetAlert\Facades\Alert;

class Controller extends BaseController
{
    (...)

    public function __construct()
    {
        $this->middleware(function($request,$next){
            if (session('success')) {
                Alert::success(session('success'));
            }

            if (session('error')) {
                Alert::error(session('error'));
            }

            return $next($request);
        });
    }
}


Enter fullscreen mode Exit fullscreen mode

Now, everytime you will redirecting with flashed session data, you will see the alert.

Let's do this, supposing you are creating an item, do this in your ItemsController app/Http/Controllers/ItemsController.php :



use App\Models\Item;
use Illuminate\Validation\ValidationException;

class ItemsController extends Controller
{
    (...) 

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'item title',
            'price' => 10
        ]);

        try {
            Item::create([
                'name' => $request->name,
                'price' => $request->price
            ]);

            return redirect()->back()
                ->with('success', 'Created successfully!');
        } catch (\Exception $e){
            return redirect()->back()
                ->with('error', 'Error during the creation!');
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

Here we go! Was very simple, isn't it ?
Alt Text
Yes that's cool but it doesn't works with form validation... 😈

Use with form validation

There is a little trick to use the SweetAlert2 with the native Laravel form validation.

First, you must add a specific flash session name in the base controller app/Http/Controllers/Controller.php that we modified above :



(...)

class Controller extends BaseController
{
    (...)

    public function __construct()
    {
        $this->middleware(function($request,$next){
            if (session('success')) {
                Alert::success(session('success'));
            }

            if (session('error')) {
                Alert::error(session('error'));
            }

            if (session('errorForm')) {
                $html = "<ul style='list-style: none;'>";
                foreach(session('errorForm') as $error) {
                    $html .= "<li>$error[0]</li>";
                }
                $html .= "</ul>";

                Alert::html('Error during the creation!', $html, 'error');
            }

            return $next($request);
        });
    }
}


Enter fullscreen mode Exit fullscreen mode

And still in the ItemsController app/Http/Controllers/ItemsController.php, just before the try catch, you must replace the precedent validation bloc by the Validator facades, like this :



(...)
use Illuminate\Support\Facades\Validator;

class ItemsController extends Controller
{
    (...) 

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'price' => 'required|int'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->with('errorForm', $validator->errors()->getMessages())
                ->withInput();
        }

        try {
            Item::create([
                'name' => $request->name,
                'price' => $request->price
            ]);

            return redirect()->back()
                ->with('success', 'Created successfully!');
        } catch (\Exception $e){
            return redirect()->back()
                ->with('error', 'Error during the creation!');
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

Here we go! Now, when you have a failed validation, you must see the error alert with the corresponding fields.
Alt Text

Little tip

If you want to keep the fields filled when validation fails, you must use the withInput() method in your controller and use the old() method as the value in your blade, like following.

In your controller app/Http/Controllers/ItemsController.php :



if ($validator->fails()) {
     return redirect()->back()
          ->with('errorForm', $validator->errors()->getMessages())
          ->withInput();
}


Enter fullscreen mode Exit fullscreen mode

In your blade resources/views/items/create.blade.php :



<input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}">

Enter fullscreen mode Exit fullscreen mode




The final word 💬

Thanks for reading this little tutorial, feel free to add a comment to share your opinions! 😀☕

Some links :

Top comments (5)

Collapse
 
frenchcodingvibes profile image
French Coding Vibes

Great work my friend !

Collapse
 
jeromew90 profile image
Jérôme W

Thank you 😀

Collapse
 
daking24 profile image
King David • Edited

Nice TIPS man with the old() in the blade

Collapse
 
alphaolomi profile image
Alpha Olomi

Its worth mentioning that the package already got support for middleware and there is no need to create your own

see realrashid.github.io/sweet-alert/m...

Collapse
 
logicsatinn profile image
Calvin Jackson

Middleware is a bit fuzzy though