Dialog alert is necessary for the Web or mobile application. It gives an alert before performing a certain activity. Suppose, you are going to perform a delete action over a data set. Then that time it helps you to do a valid activity on it. In case, if you clicked delete action accidentally, and you didn’t have the dialog alert. That action will perform the delete operations on your data set. Sometimes, you may lose your important data. This is the measure reason to have a dialog alert in your application. JavaScript provides the Sweet Alert library. It contains different kinds of alerts like info, success, warning, error, etc. So, based on your activity type, you can use any of the alert types. Today, in this post, we will gonna implement the Sweet Alert in Laravel 8 application.
Prerequisites
You will require to have the below configuration for creating a Laravel 8 application.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- Composer
Create Laravel 8 Project For Sweet Alert
For creating the Laravel 8 project, I will use composer. You can create the project using the Laravel installer too. Hence, open the terminal or command prompt and hit the below command.
composer create-project --prefer-dist laravel/laravel blog
The above command will install the Laravel 8. Once, it is completed, let’s configure the database for it.
How to Use Toastr JS in Laravel 8 For Showing Notification
Configure Database For Sweet Alert Project
I have created a database named blog and configured the database credentials in the project environment.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=root
Once, it is done, let’s install the Sweet Alert package in Laravel 8.
Install Sweet Alert Package in Laravel 8
The composer dependency manager has the package for the Sweet Alert. Hence, you can install it easily from the terminal.
composer require realrashid/sweet-alert
The above command will install the package inside the project.
After installing the package, you will need to publish its configuration settings.
php artisan sweetalert:publish
Now, you are done with the configuration. Let’s apply it to the views so that we can see the result.
How to Create Custom Password Reset Link in Laravel 8
Create a Model and Migration
For the demo purpose, I will store the data in the database. Then on the basis of the operation, I will show the alert message. Hence, it will require a migration and a model. Therefore, I will use the default one inside Laravel.
So, under the database/migrations folder, look for the users table. Now, put the below schema.
<?php
use Illuminate\Database\Migrations\Migration
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Correspondingly, you will need to set the fillable data in the user model.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Now, migrate the table using the below command.
php artisan migrate
It will migrate the users table schema inside the database. That’s it for the database and model.
In the next step, you will require a controller and a view file. Actually, we installed the package for the Sweet Alert using the composer. Hence, it will pass the Alert through the controller to the view file. Also, inside the view, you will need to include the alert. I will show you.
Pass Data to Master Layout By Service Provider in Laravel 8
Create a Controller For Generating Alert Message
Here, I am going to create a controller and a blade file. Inside the controller, we will use the alert type and that will gonna displayed in our view file.
php artisan make controller::UserController
After creating the controller, add the below snippet. In the below snippet, we have two functions.
- The first one is for rendering the view.
- Last function is for storing the form values to the database table. We will create this view in the next step.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use RealRashid\SweetAlert\Facades\Alert;
class UserController extends Controller
{
/**
* @param NA
* @return view
*/
public function index() {
return view('users');
}
/**
* @param request
* @return response
*/
public function store(Request $request) {
$request = $request->all();
$request['password'] = Hash::make($request['password']);
$user = User::create($request);
if ($user) {
Alert::success('Success', 'You\'ve Successfully Registered');
return back();
}
else {
Alert::error('Failed', 'Registration failed');
return back();
}
}
}
Inside the store() function, I got the request data from the form inputs. After that, I am storing it in the users table through the mass assignment (model). In the response, if the data is inserted, then it will generate the Alert with the type of success. Also, I have set the message for it.
Similarly, if the data isn’t inserted, then it will generate the Alert with a type error. And it has the message accordingly. That’s it for the functionality in the controller.
Redirect HTTP to HTTPS Using Middleware in Laravel 8
Create a View For Displaying Sweet Alert Message
Here, you will need to create a view as you pass in the controller function. Therefore, I am creating a view with the name users.blade.php. After creating the view, you need to include the Alert inside the body.
@include('sweetalert::alert')
This is required to capture the SweetAlert message whatever is generated from the controller.
<!doctype html>
<html lang="en">
<head>
<title>Programming Fields - Sweet Alert</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="icon" type="image/x-icon" href="/images/favicon.ico">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
@include('sweetalert::alert')
<div class="container my-5">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-8 col-12 m-auto">
<form action="{{ url('store') }}" method="POST">
@csrf
<fieldset class="shadow p-4">
<legend class="fw-bold border-bottom">Sweet Alert in Laravel 8</legend>
<div class="form-group pt-3">
<label> Name </label>
<input type="text" class="form-control" name="name" placeholder="Name">
</div>
<div class="form-group pt-3">
<label> Email </label>
<input type="text" class="form-control" name="email" placeholder="Email">
</div>
<div class="form-group pt-3">
<label> Password </label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-success mt-4"> Save </button>
</fieldset>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"
integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"
integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous">
</script>
{{-- toastr js --}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.0/js/toastr.js"></script>
</body>
</html>
That’s it for the code snippet. Lastly, you need to add the routes.
Create REST API in Laravel 8 Using JWT Authentication
Create Routes
For adding the routes, navigate to the web.php file and add the below routes.
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [UserController::class, 'index']);
Route::post('store', [UserController::class, 'store']);
Now, it’s time to check the result for the Sweet Alert.
How to Create Github Login in Laravel 8 Using Socialite
Result of Sweet Alert in Laravel 8
Run the application, and access the route in the browser. You will have to below form. Fill up the form and submit it.
After submitting the form, you will get a successful response if the record is inserted.
Other Alert Types in Sweet Alert
The Sweet Alert provides different types of alert types. You can use these alert types as per your requirements.
Alert::info()
Alert::warning()
Alert::error()
Alert::question()
Alert::image()
Alert::html()
You can use these alert types by passing the parameters as shown below.
Alert::info('Info Title', 'Info Message');
Alert::warning('Warning Title', 'Warning Message');
Alert::error('Error Title', 'Error Message');
Alert::question('Question Title', 'Question Message');
Alert::image('Image Title!','Image Description','Image URL','Image Width','Image Height');
Alert::html('Html Title', 'Html Code', 'Type');
Conclusion
In Laravel 8, we implemented the Sweet Alert for displaying the alert messages. Sweet Alert provides different types of alert types. You can use these alert types for different cases. You can use the CDN of Sweet Alert for using in your application. But, inside the composer, you can find the package easily. So, it is up to whatever approach you want, you can use it.
Leave a Reply