Laravel PHP Beginners guide-CRUD operations(Using ajax)

Lahiru Ariyasinghe
App Dev Community
Published in
9 min readDec 5, 2020

--

Today, I am going to share with my knowledge about Laravel PHP CRUD operations. We can do this easily by using ajax jQuery with validations in simple easy way. Also you can learn so much of fundamental practices about Laravel PHP framework. First of all you want to install the XAMPP and PHP on your PC. Then you want to install the composer as well. After You can initiate a Laravel project on your C:\xampp\htdocs\ directory. Let go with following steps.

Install Laravel Framework and Initialize the project

Go to the C:\xampp\htdocs\ laravel. Run the following command on cmd. Then you can load all components of the composer.

composer

Then install the Laravel framework by running the following command,

composer create-project --prefer-dist laravel/laravel crud_project

This command make a new project inside your C:\xampp\htdocs\ laravel folder naming as “crudproject”. Then you want to open this project folder, on your favorite code editor. Then we can work on the project. To start the project running, you want to run the following command. Please run the command and check if the project is run or not,

php artisan serve

The command will look following if it work perfectly,

You want to run the showing URL( http://127.0.0.1:8000 ) on your browser and check whether the initial Laravel screen shows correctly. If so, you just finish the project initializing step successfully.

How to make Mysql Database connection Laravel

For making database connection with Mysql in Laravel so you have to open .env file in your editor.

After define database credential in this .env file now we want to go to config/database.php file and open this file and change credentials as following.

After you make the database connections, You can ensure the project is working correctly or not. Run the php artisan serve on cmd and check the url http://127.0.0.1:8000 It will show as folloewing on your favourite browser.

Then you need to make a model for creating a table in the “employee” database.

php artisan make:model Employee -m

This command will generate migration file for our Crud Operation in database/migrations folder. So we have to open that file in editor and add following code in it.

After write above code in that migration file now we want to migrate this table into MySQL database, so we have go to command prompt and write following command.

php artisan migrate

This command will migrate employees table into employee database and make employees table in MySQL database. That employees table has five columns. So using this way, we can make tables in MySQL database.

Make a Controller to control the crud operations

Now we are ready to implement the CRUD operations. For that, We want to create a controller first. This Controller contained the all resource methods what we are going to execute when we want such as create, delete, update and read (index method).

php artisan make:controller EmployeeController --resource

This command will generate a controller at app/Http/Controllers/EmployeeController.php. The controller will contain a method for each of the available resource operations. Next, you want to register the resourceful route to the controller in routes/web.php file.

Route::resource('employee', 'EmployeeController');

This single route implementation will creates all routes to handle a variety of actions on the employee resource. As mentioned before, The generated controller will already have methods for each of these actions, including notes informing you of the URIs they handle and HTTP verbs.

Then you need to create a view at resources/views/employee/list.blade.php. This view is the .blade.php file, which display and execute all frond end operations. This view will initialize at the index method of the EmployeeController as follows. Here the employee.list file would create inside the resoures/view/employee folder.

public function index(){
return view('employee.list');
}

Still this is not the time to run the project. We need to add the yajra data-table library vendor/yajra/laravel-datatables-oracle. So please run and follow the steps.

composer require yajra/laravel-datatables-oracle:"~9.0"

Then in your config/app.php make changes of yajra datatable as follows.

'providers' => [
............
Yajra\Datatables\DatatablesServiceProvider::class,

],
'aliases' => [
................
'DataTables' => Yajra\DataTables\Facades\DataTables::class,

],

After adding service provider and alias details, now we want to publish following package under this application, so we can use this package under Laravel. So for this we have to go to command prompt and write following command.

composer dumpautoload

After we installed the yajra DataTable libraries, then we can read data of the table including following getData() method in EmployeeController.php. This is a new method inside the Controller.

public function getData(){
$employees = Employee::select('first_name', 'last_name');
return $employees;
}

Then register that route at web.php

Route::get('employee/getdata', 'EmployeeController@getdata')->name('employee.getdata');

Lastly we want to send ajax request from list.blade.php file to this getdata() method of EmployeeController.php file. Below you can see the ajax request code inside the <script> tags.

<!DOCTYPE html>
<html>
<head>
<title>Datatables Server Side Processing in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
<br />
<h3 align="center">Laravel Beginners guide - CRUD operations ()(using Ajax)</h3>
<br />
<table id="employee_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
</table>
</div>

<script type="text/javascript">
$(document).ready(function() {
$('#employee_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('employee.getdata') }}",
"columns":[
{ "data": "first_name" },
{ "data": "last_name" }
]
});
});
</script>
</body>
</html>

Lastly, we want to show output in browser, so we have to go to command prompt and write this command for run Laravel application. Before that, don’t forget to add few data rows to the employee table. or you can make a seeder file and run to feed data. Here I added some data rows manually. The result is looks like following.

php artisan serve

How to Create/Add Data into MySQL Table in Laravel

So our next task is to add data to the table. We can use a bootstrap form model to add data.

<div id="employeeModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="employee_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Add New Employee</h4>
</div>
<div class="modal-body">
{{csrf_field()}}
<span id="form_output"></span>
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
</div>
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="employee_id" id="employee_id" value="" />
<input type="hidden" name="button_action" id="button_action" value="insert" />
<input type="submit" name="submit" id="action" value="Add" class="btn btn-info" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>

Also the following JavaScript handle the submit function of the employee_form.

$('#employee_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"{{ route('employee.store') }}",
method:"POST",
data:form_data,
dataType:"json",
success:function(data)
{
if(data.error.length > 0)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
}
$('#form_output').html(error_html);
}
else
{
$('#form_output').html(data.success);
$('#employee_form')[0].reset();
$('#action').val('Add');
$('.modal-title').text('Add Data');
$('#button_action').val('insert');
$('#employee_table').DataTable().ajax.reload();
}
}
})
});

In controller side, The ajax request call to the store() method.

function store(Request $request){$validation = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
]);
$error_array = array();
$success_output = '';
if ($validation->fails())
{
foreach ($validation->messages()->getMessages() as $field_name => $messages){
$error_array[] = $messages;
}
}
else
{
if($request->get('button_action') == 'insert')
{
$employee = new Student([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name')
]);
$employee->save();
$success_output = '<div class="alert alert-success">Data Inserted</div>';
}
}
$output = array(
'error' => $error_array,
'success' => $success_output
);
echo json_encode($output);
}

How to Update Data in MySQL Table of Laravel

So our next task is to add data to the table. We can use the add bootstrap form model to update data. The following method added into the JavaScript method and it will call when click on edit button.

$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
$('#form_output').html('');
$.ajax({
url:"{{route('ajaxdata.edit')}}",
method:'get',
data:{id:id},
dataType:'json',
success:function(data)
{
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#employee_id').val(id);
$('#employeeModal').modal('show');
$('#action').val('Edit');
$('.modal-title').text('Edit Data');
$('#button_action').val('update');
}
})
});

Then the controller side should update as following. Here the store method reused, but we can use the update method as we need.

function store(Request $request)
{
$validation = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
]);
$error_array = array();
$success_output = '';
if ($validation->fails())
{
foreach ($validation->messages()->getMessages() as $field_name => $messages)
{
$error_array[] = $messages;
}
}
else
{
if($request->get('button_action') == 'insert')
{
$employee = new Employee([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name')
]);
$employee->save();
$success_output = '<div class="alert alert-success">Data Inserted</div>';
}
if($request->get('button_action') == 'update')
{
$employee = Employee::find($request->get('id'));
$employee->first_name = $request->get('first_name');
$employee->last_name = $request->get('last_name');
$employee->save();
$success_output = '<div class="alert alert-success">Data Updated</div>';
}
}
$output = array(
'error' => $error_array,
'success' => $success_output
);
echo json_encode($output);
}

How to Delete Data in MySQL Table of Laravel

Finally our next task is to delete data to the table. The following method added into the JavaScript method and it will call when click on delete button.

$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
if(confirm("Are you sure you want to Delete this data?"))
{
$.ajax({
url:"{{route('ajaxdata.destroy')}}",
method:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#employee_table').DataTable().ajax.reload();
}
})
}
else{
return false;
}
});

Then the EmployeeController should be update as following. Here the store method reused, but we can use the destroy method as we need.

function destroy(Request $request)
{
$employee = Employee::find($request->input('id'));
if($employee->delete())
{
echo 'Data Deleted';
}
}

After everything changed as above, The list.blade.php file looks like following.

<!DOCTYPE html>
<html>
<head>
<title>Datatables Server Side Processing in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h3 align="center">Datatables Server Side Processing in Laravel</h3>
<div align="right">
<button type="button" name="add" id="add_data" class="btn btn-success btn-sm">Add</button>
</div>
<br />
<table id="student_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<div id="studentModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="student_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Add Data</h4>
</div>
<div class="modal-body">
{{csrf_field()}}
<span id="form_output"></span>
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
</div>
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="student_id" id="student_id" value="" />
<input type="hidden" name="button_action" id="button_action" value="insert" />
<input type="submit" name="submit" id="action" value="Add" class="btn btn-info" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#student_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('ajaxdata.getdata') }}",
"columns":[
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "action", orderable:false, searchable: false}
]
});
$('#student_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"{{ route('ajaxdata.postdata') }}",
method:"POST",
data:form_data,
dataType:"json",
success:function(data)
{
if(data.error.length > 0)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
}
$('#form_output').html(error_html);
}
else
{
$('#form_output').html(data.success);
$('#student_form')[0].reset();
$('#action').val('Add');
$('.modal-title').text('Add Data');
$('#button_action').val('insert');
$('#student_table').DataTable().ajax.reload();
}
}
})
});
$('#add_data').click(function(){
$('#studentModal').modal('show');
$('#student_form')[0].reset();
$('#form_output').html('');
$('#button_action').val('insert');
$('#action').val('Add');
$('.modal-title').text('Add Data');
});
$('#student_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"{{ route('ajaxdata.postdata') }}",
method:"POST",
data:form_data,
dataType:"json",
success:function(data)
{
if(data.error.length > 0)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
}
$('#form_output').html(error_html);
}
else
{
$('#form_output').html(data.success);
$('#student_form')[0].reset();
$('#action').val('Add');
$('.modal-title').text('Add Data');
$('#button_action').val('insert');
$('#student_table').DataTable().ajax.reload();
}
}
})
});
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
$('#form_output').html('');
$.ajax({
url:"{{route('ajaxdata.fetchdata')}}",
method:'get',
data:{id:id},
dataType:'json',
success:function(data)
{
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#student_id').val(id);
$('#studentModal').modal('show');
$('#action').val('Edit');
$('.modal-title').text('Edit Data');
$('#button_action').val('update');
}
})
});
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
if(confirm("Are you sure you want to Delete this data?"))
{
$.ajax({
url:"{{route('ajaxdata.removedata')}}",
method:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#student_table').DataTable().ajax.reload();
}
})
}
else{
return false;
}
});
});
</script>
</body>
</html>

--

--