When you want to submit a form in Laravel 6 without reloading the page then you will have to use AJAX. It prevents the page reload when you request to the server for the data. That means when you want to send and receive data from the server it will pass the data asynchronously. AJAX makes requests internally which do not refresh the page. This makes the webpages faster and optimized. You can use AJAX in Laravel 6 for creating any application. In this post, I am gonna show you how you can use AJAX in Laravel 6. For demonstration purposes, I am gonna create a Laravel ajax todo application. In the previous post, I have shown sending emails in Laravel 6 using Gmail SMTP.
Prerequisites of Project
- I am assuming you have the basic concept of AJAX.
- You required PHP (version >=7.3.9)
- MySQL (version > 5)
- Editor (VS Code, Sublime, PHP Storm)
Use AJAX in Laravel 6
We are going to use AJAX in Laravel 6. So for implementing AJAX, I will be creating a ToDo application. First of all, I will create a new Laravel 6 project by entering the below command.
composer create-project --prefer-dist laravel/laravel ajax-todo
It will take few minutes for creating the project.
After creating the project, just open it in the editor.
How to Use Yajra Datatables in Laravel 6
Create and Configure the Database
Open the MySQL command line or if you are using phpMyAdmin then create a new database there.
CREATE DATABASE laravel6_ajax_todo;
After creating the database, we’ll configure the database credentials inside the project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel6_ajax_todo
DB_USERNAME=root
DB_PASSWORD=root
Open .env file and replace your details with the above database details.
Add UI Scaffolding in Laravel 6
In Laravel 6, the frontend scaffolding has been moved to the ui –dev package. So, we will have to install it first.
composer require laravel/ui --dev
Laravel 6 REST API For ToDo Application with Passport Auth
Add Node Modules in Laravel 6
Laravel comes up with the default front end dependencies. So, we just need to install it inside the project. We will require to add Node Modules inside the project by hitting the below command.
npm install
After adding the node modules inside the project, we’ll need to run the development mode.
npm run dev
The above command will install the required dependencies in your project.
After installing the dependencies, just navigate to the Public folder. You will see there CSS and js folder.
Run the project by entering the below command.
php artisan serve
How to Integrate Laravel 6 Application with Firebase
Create Models and Migration
In the next step, we’ll create a Model for managing the functionalities of the tasks. Laravel provides the model and migration together. The migration defines the table schema of the database. Every model belongs to a specific table.
php artisan make:model Task --migration
The above command will create a Model inside the App with the name Task.
You can see the migration file inside the database folder of your project.
Open the create_tasks_table.php file inside the migration and replace it with the below schema.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('task_title');
$table->text('description');
$table->text('category');
$table->text('duration');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tasks');
}
}
RESTful APIs in Laravel 6 with Passport Authentication
Mass Assignment of Model
Now, open the model (Task.php) and add the fillable data.
class Task extends Model
{
protected $fillable = [
'task_title', 'description', 'category', 'duration'
];
}
Migrate Table Schema
In the next step, we will have to migrate the database schema. So for this just hit the below command in the terminal.
php artisan migrate
This command will generate the tables inside the database.
You can check the table schema inside the database.
Create Controller
So to manage the functionalities of the tasks, I will create a Controller. Now, create the task controller by hitting the below command.
php artisan make:controller TaskController
Now, paste the below code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Task;
class TaskController extends Controller
{
// --------------------- [ Load Task Listing View ] -----------------------
public function index()
{
return view('task/index');
}
// --------------------- [Load Create task view ] -------------------------
public function create()
{
return view ('task/create');
}
// ------------------- [ Save Task ] ----------------------------
public function storeTask(Request $request)
{
$validator = $request->validate(
[
'task_title' => 'required',
'description' => 'required',
'category' => 'required',
'duration' => 'required'
]
);
$input = $request->all();
$task = Task::create($input);
if(!is_null($task)) {
return response()->json(['status' => 'success', 'message' => 'Task created successfully']);
}
else {
return response()->json(['status' => 'failed', 'message' => 'Failed to create task']);
}
}
How to Upload Files and Images in Laravel 6 with Validation
Create Views
According to this post, I will be creating the following views inside the resource->views.
- layout.blade.php
- create.blade.php
// layout.blade.php
<!doctype html>
<html lang="en">
<head>
<title> AJAX Todo Application </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
<div class="container mt-4">
@yield('content')
</div>
<!-- <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
@extends ('task/layout')
@section ('content')
<div class="row mt-3">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto ">
<div class="card shadow">
<div class="card-header bg-primary">
<div class="card-title font-weight-bold text-white "> Laravel 6 AJAX Todo Application </div>
</div>
<form method="post" id="taskForm">
{{csrf_field() }}
<div class="card-body">
<!-- --- Display success message ----- -->
@if(Session::has('success'))
<div class='alert alert-success'>
{{ Session::get('success') }}
@php
Session::forget('success')
@endphp
</div>
@endif
<div class="form-group">
<label for="task_title"> Task Title </label>
<input type="text" class="form-control" name="task_title" id="task_title" placeholder="Task Title">
</div>
<div class="form-group">
<label for="description"> Description </label>
<input type="text" class="form-control" name="description" id="description" placeholder="Description">
</div>
<div class="form-group">
<label for="category"> Category </label>
<input type="text" class="form-control" name="category" id="category" placeholder="Category">
</div>
<div class="form-group">
<label for="duration"> Duration </label>
<input type="text" class="form-control" name="duration" id="duration" placeholder="Duration">
</div>
<div class="card-footer">
<button type="button" id="saveBtn" class="btn btn-success">Save Task</button>
</div>
<div id="result"></div>
</form>
</div>
</div>
</div>
@endsection
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// Pass csrf token in ajax header
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Trigger ajax function on save button click
$("#saveBtn").click(function() {
var formData = $("#taskForm").serialize();
$.ajax({
type : "POST",
url : "store",
data : formData,
dataType : "json",
success: function(res) {
if(res.status == "success") {
$("#result").html("<div class='alert alert-success'>" + res.message + "</div>");
}
else if(res.status == "failed") {
$("#result").html("<div class='alert alert-danger'>" + res.message + "</div>");
}
}
});
});
});
</script>
Laravel 6 Custom Login and Registration with Session
Add Routes For Task Controller
In the next step, add the following routes in the routes/web.php file.
Route::get("task/", "TaskController@index");
Route::get("task/create", "TaskController@create");
Route::post('task/store', 'TaskController@storeTask');
Once you have done with the above steps, run the project by artisan serve command.
php artisan serve
When your application will run, it will look like this.
For creating the task the route URL will be –
localhost:8000/task/create
When you will run the application, this will load the create task view as shown below.
How to Implement Pagination in Laravel 6 with Example
Now, create a task by filling up the details. You will see the form won’t refresh while creating the Task. I have created some tasks here.
For retrieving the task you can enter the URL –
localhost:8000/task/create
Now, you can see all the tasks that have been created are showing here. Also, I have added navigation to open the create task view.
Conclusion
That’s all for this tutorial of AJAX in Laravel 6 with a Todo application. Finally, we learned how to use AJAX in Laravel for creating any application. By using this concept you can build more creative applications. AJAX makes faster to our application. I hope guys this post will guide you in learning and using the AJAX in Laravel 6.
Leave a Reply