While creating a web application, it is common to show the notification on the client-side for a certain action. Suppose, for adding a new record, or updating a record. On completion of that action, we show a notification. It shows the response based on that action. There are lots of libraries for showing notifications or alert messages. Javascript provides the Toastr js library that is used to display the notification. This is very simple and easy to implement on any web application. It is open source and you can implement it through CDN, npm package, or yarn package. The Toastr js has different types of notifications like success, info, warning, and error. In this post, we will see how you can implement Toastr JS in Laravel 8 application.
This is very similar to the bootstrap alert component. This takes options of some parameters to control the animation, timeout, positioning, etc. We will see by implementing it in the Laravel 8 project.
How to Create Custom Password Reset Link in Laravel 8
Toastr JS
The Toastr js provides the different types of notifications. The types are –
- error
- success
- info
- warning
After adding the CDN or installing it through npm, you can access it through the below functions-
toastr.error();
toastr.success();
toastr.info();
toastr.warning();
You can pass the message inside the function whatever you want. For the advanced management of Toastr js, you can pass the options in the form of objects directly. We will see that in the example. So, let’s continue with the project.
Prerequisites
For creating a new project in Laravel 8, your system should follow the below requirements-
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- Composer
We will create the Laravel 8 project using the composer.
Create Project For Toastr JS in Laravel 8
Open the terminal and hit the below command. It will create the project folder and install the Laravel 8 setup.
composer create-project --prefer-dist laravel/laravel blog
After successful installation of Laravel 8, navigate to the project folder and open it inside the VS code.
Pass Data to Master Layout By Service Provider in Laravel 8
Create and Configure Database
We will create a database and configure it with the Laravel 8 project. Firstly, create a database in MySQL. Then look for the .env file inside the project and connect it as shown below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=root
In the next step, we will create a model and migration for performing database operations.
Create a Model and Migration For Toastr JS
By default, Laravel provides a model and migration for the users. Hence, we will use the same model and migration for now. So, initially, open the users table migration available in the database/migrations folder. Now, make it as same as 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');
}
}
Now, let’s migrate the schema inside the database. Hence, hit the migrate command in the terminal.
php artisan migrate
After completing the migration, let’s add fillable data to the model.
Redirect HTTP to HTTPS Using Middleware in Laravel 8
Add Fillable Data in Users Model
For adding the fillable data, navigate to the Users model. In the users model, you will see the default fillable array with the fields. If you want to add more fields as per the schema then you may add them here.
<?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',
];
}
In the next step, you will require to have a controller.
Create REST API in Laravel 8 Using JWT Authentication
Create a Controller
You need to create a controller for managing the form activities. On the basis of form action, we will implement the Toastr js in Laravel 8.
php artisan make controller:UserController
After creating the controller, let’s put the code inside it. Mainly, we will handle the form request and on submitting the form, we will show the response in Toastr js.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
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) {
return back()->with('success', 'Success! User created');
}
else {
return back()->with('failed', 'Failed! User not created');
}
}
}
In the above code, we have two functions. The first one (index) is for rendering the view that will contain a form. The store function is for handling the form request.
Let’s create a view for this one.
Create a View For Form Handling
Navigate to the resources/views folder. Then create a blade file inside it. The name of the blade file will be users.blade.php. We already rendered this blade file inside the UserController.php. Hence, put the same name.
In this demo, I will implement Toastr JS using the CDN. Hence, you can use the Toastr JS CDN in the application.
<!-- CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.0/css/toastr.css" rel="stylesheet" />
<!-- JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.0/js/toastr.js"></script>
<!doctype html>
<html lang="en">
<head>
<title>Programming Fields - Toastr JS</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">
{{-- toastr --}}
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet" />
</head>
<body>
<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">Toastr js 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.0.1/js/toastr.js"></script>
<script>
$(document).ready(function() {
toastr.options.timeOut = 10000;
@if (Session::has('error'))
toastr.error('{{ Session::get('error') }}');
@elseif(Session::has('success'))
toastr.success('{{ Session::get('success') }}');
@endif
});
</script>
</body>
</html>
I have created a basic form with the fields name, email, and password in the above blade file. Also, I have captured the message from the Laravel session. This session message is coming from the controller. On the form submit, it will return the response as success or failed. In both cases, it will display the notification in different types.
Result of Toastr JS Notification
So, let’s come to the result. The form will look like this –
After filling up the form, let’s submit it. If the record is inserted into the database, you will get the success response in the session. After that, the page will reload, and through jQuery, we captured the Laravel session on the document load event.
In the response, it will display the session message.
Similarly, if there will be an error then it will return the error message and the Toastr type will be an error. The background color of Toastr will be red.
How to Create Github Login in Laravel 8 Using Socialite
You can implement its different types as you required in the application. For more details, you may visit the Toastr.js official site.
Conslusion
Finally, we got the idea for the implementation of Toastr js in the Laravel 8 project. The Toastr JS library is simple and very easy to manage. It can be used through CDN, or npm install. You can customize the positioning for displaying notifications like Top Right, Top Left, Bottom Right, Bottom Left, etc. Also, it allows customizing the animation and timeout to fade out the notification. So, I hope you will find helpful to this post. For any kind of issue or doubt, you may ask through the comment. You will get a response immediately with the possible solution.
Leave a Reply