How to use SweetAlert2 in Laravel 8 using Composer
Tags: laravel, php
Published: 2021-05-23 09:48:10

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ovjvxyupds5o3mlws8k.jpg)

**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](https://realrashid.github.io/sweet-alert/), first thing you need to do is to use Composer to add the package to your project's dependencies : 
```bash
composer require realrashid/sweet-alert
```

After installing the sweet-alert package, register the service provider in your `config/app.php` configuration file : 
```php
'providers' => [
    /*
    * Package Service Providers...
    */
    RealRashid\SweetAlert\SweetAlertServiceProvider::class,
],
```

Also, add the Alert facade to the aliases array in the same configuration file :
```php
'aliases' => [
    (...)
    'Alert' => RealRashid\SweetAlert\Facades\Alert::class,
],
```

Finaly, you must add the sweetalert view in your master layout : 
```php
@include('sweetalert::alert')
```

And run the below command to publish the package assets : 
```bash
php artisan sweetalert:publish
```

# Use
To use SweetAlert2 globally in your project, you must add a middleware in your base controller `app/Http/Controllers/Controller.php` : 
```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);
        });
    }
}
```

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` : 
```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!');
        }
    }
}
```

Here we go! Was very simple, isn't it ?
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6qbqflmj75x1sjkyygw.png)
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 :
```php
(...)

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);
        });
    }
}
```

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 : 
```php
(...)
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!');
        }
    }
}
```

Here we go! Now, when you have a failed validation, you must see the error alert with the corresponding fields.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2u8jqs9y02zmhsb82a1b.png)

# 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` :
```php
if ($validator->fails()) {
     return redirect()->back()
          ->with('errorForm', $validator->errors()->getMessages())
          ->withInput();
}
```
In your blade `resources/views/items/create.blade.php` :
```php
<input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}">
```

# The final word 💬
Thanks for reading this little tutorial, feel free to add a comment to share your opinions! 😀☕

Some links :
* [Official GitHub sweet-alert library](https://github.com/realrashid/sweet-alert)
* [Official documentation](https://realrashid.github.io/sweet-alert/)