Jérôme W
Posted on May 23, 2021
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
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,
],
Also, add the Alert facade to the aliases array in the same configuration file :
'aliases' => [
(...)
'Alert' => RealRashid\SweetAlert\Facades\Alert::class,
],
Finaly, you must add the sweetalert view in your master layout :
@include('sweetalert::alert')
And run the below command to publish the package assets :
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
:
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
:
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 ?
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);
});
}
}
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!');
}
}
}
Here we go! Now, when you have a failed validation, you must see the error alert with the corresponding fields.
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();
}
In your blade resources/views/items/create.blade.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 :
Posted on May 23, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.