logo

With More Than 3 Years Of Experience, We Help To Develop Your Business, We Provide The Best Service That Comes With The Best Results.

Contact Info

+(971) 5549-46482

info@webdesigningindubai.com

webdesigningindubai47@gmail.com

Al Khaleej Street

Dubai, United Arab Emirates

Monday - Sunday, 9am - 5pm,

Friday - CLOSED

Our Blog

blog
  • Sep 21, 2019 04:21:56 pm
  • Comment 13
  • Laravel
Ajax CRUD Using Laravel Framework

First, I will give you an introduction about our company. We start a business in Dubai and our website name is Web Designing in Dubai. And also we start to give training about Laravel, PHP, CSS, HTML or etc. So this is our first blog post. Please keep sharing this post because you someone can learn from our website.

As you know, all very well laravel is the most secure PHP Framework which helps you to develop a more complex application. The Laravel framework features a few system needs. All of those needs square measure glad by the Laravel Homestead virtual machine, therefore it's extremely counseled that you use Homestead as your native Laravel development atmosphere. However, if you're not exploitation Homestead, you'll have to be compelled to certify your server meets the subsequent requirements:

  • PHP >= 7.2.0
  • BCMath PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension
  • Mbstring PHP Extension
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension

Installation Laravel  Ajax CRUD Using cmd:

If you want to install laravel on your system then first you need to open cmd. Then you need to go xampp folder using cmd then goto htdocs folder using cmd. After that, you need to run this command on cmd.

composer create-project laravel/laravel LaravelAjaxCrud

 After Running the command on the cmd, then cmd start downloading laravel files. He makes a folder in htdocs which name is LaravelAjaxCurd. Now next step is that you need to write on cmd.

cd LaravelAjaxCrud

Now you are in the folder which you created in the htdocs folder. Now you need to write the command. 

php artisan serve

After that, you need to open Google Chrome or any other browser which you want to use. Now in the search bar, you need to write 127.0.0.1.8000. Now you can see the laravel project install successfully. 

Ajax CRUD using Laravel

Now we need to start creating controllers or models or migrations for our CRUD operations. Before running the command, you need to open cmd and press (CTRL + C). Now run the command on cmd for creating the Model, Controller, and Migration.

php artisan make:model LaravelAjaxCrud -mcr

when you run this command, then three things should b created. The first one is the Controller with resources and the second thing is the Model and the third thing is migration. Now we need to define the route for display the data of the form while using we can add edit or delete the form data.

Route::resource('/form','LaravelAjaxCrudController');

After that, we need to create a view to display the data. But First, we need to configure database and create columns in our migration file. We use 3 input fields like Name, Email, Phone. Now Our Migration file looks like that.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateLaravelAjaxCrudsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('laravel_ajax_cruds', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->nullable();
            $table->string('email')->nullable();
            $table->string('phone')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('laravel_ajax_cruds');
    }
}

Now we run artisan migrate command. Before Running the command we need to open localhost/phpmyadmin in our google browser or any other which you are using. and create a new database. I created the database whose name is (laravelajax). If you want to use another name then you can use it. But Remember one thing put that name in .env file to. Now we run the command.

php artisan migrate

Now Database migrated successfully. Now we need to go to LaravelAjaxCrudController.php and in index function, we need to get all form data from the database. now i can show how we perform all of the steps. now i share a bit of code with you. First, I show the view file.

Now i can explain the below code.

  1. In the First Step, you need to do all of the above steps which I mention.
  2. After that, you need to code the index.blade.php file code and paste it into resources/view/index.blade.php.
  3. Then you need to copy the controller code which I gave below and paste into the file app/Http/Controllers/LaravelAjaxCrudController.php.
  4. After that, you need to copy the web.php code and paste it into routes/web.php.
  5. Finally, Now all the things are set now you need to run this code. 
  6. To run this code you need to run the command in CMD php artisan serve.
  7. Here you can see the code run successfully. Enjoy it.

resources/view/index.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>List of All Form Data</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<style>
.main-container
{
margin-top: 50px;
}
.main-container h2
{
text-align: center;
font-weight: bold;
color: black;
}
.main-container p
{
text-align: center;
font-weight: bold;
color: black;
}
.main-container a
{
font-weight: bold;
color: white !important;
}
</style>
<body>
<div class="container main-container">
<div class="row">
<div class="col-md-12">
<a class="btn btn-primary btn-sm add-new" style="margin-bottom: 10px;">Add New Record</a>
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<h2>List of All Form Data</h2>
@if($data->count() > 0)
<div class="table table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<td>Sr#</td>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</thead>
<tbody>
@foreach($data as $single_data)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $single_data->name }}</td>
<td>{{ $single_data->email }}</td>
<td>{{ $single_data->phone }}</td>
<td><input type="button" name="" id="{{ $single_data->id }}" value="Edit" class="btn btn-primary btn-sm edit-button"></td>
<td><input type="button" name="" id="{{ $single_data->id }}" value="Delete" class="btn btn-danger btn-sm delete-button"></td>
</tr>
@endforeach
</tbody>
</table>
</div>
@else
<p>There is no data Found</p>
@endif
</div>
</div>
</div>
<div class="modal" tabindex="-1" role="dialog" id="new-form">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add New Record</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body" id="new-form-content">
<form action="" id="form_submit" method="POST">
<div id="erroeorsuccess"></div>
@csrf
<label for="">Enter Name</label>
<input type="text" name="name" id="name" value="" placeholder="Enter Name" required="" class="form-control">
<label for="">Enter Email</label>
<input type="email" name="email" id="email" value="" placeholder="Enter Email" required="" class="form-control">
<label for="">Enter Phone Number</label>
<input type="tel" name="phone" id="phone" value="" placeholder="Enter Phone Number" class="form-control">
<br>
<input type="hidden" name="id" id="id" value="">
<input type="submit" name="btn" id="btn" value="Add New Record" class="btn btn-primary form-control">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger done-button">Ok Done</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".done-button").css("display", "none");
var record_id;
$(".add-new").click(function(){
$("#new-form").modal("show");
});
$("#form_submit").on('submit', function(){
event.preventDefault();
if($('#action_button').val() == 'Add New Record')
{
$.ajax({
url:"{{ route('form.store') }}",
method:"post",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: "json",
success:function(data){
var html_response = '';
if(data.errors)
{
html_response = "<div class='alert alert-danger'>";
for(var i = 0;i < data.errors.length;i++)
{
html_response += "<p>"+data.errors[i]+"</p>";
}
html_response += "</div>";
$("#erroeorsuccess").html(html_response);
}
if(data.success)
{
html_response = "<div class='alert alert-success'>";
html_response += data.success;
html_response +="</div>";
$('#form_submit')[0].reset();
$("#erroeorsuccess").html(html_response);
window.setTimeout(function(){location.reload()},1500)
}
}
});
}
if($('#btn').val() == "Update User Record")
{
$.ajax({
url:"{{ route('form.update') }}",
method:"POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: "json",
success:function(data){
var html_response = '';
if(data.errors)
{
html_response = "<div class='alert alert-danger'>";
for(var i = 0;i < data.errors.length;i++)
{
html_response += "<p>"+data.errors[i]+"</p>";
}
html_response += "</div>";
$("#erroeorsuccess").html(html_response);
}
if(data.success)
{
html_response = "<div class='alert alert-success'>";
html_response += data.success;
html_response +="</div>";
$("#erroeorsuccess").html(html_response);
window.setTimeout(function(){location.reload()},1500)
}
}
});
}
});
$(".edit-button").click(function(){
var id = $(this).attr('id');
$("#erroeorsuccess").html('');
$.ajax({
url: "{{ url('/') }}/form/"+id+"/edit",
dataType:"json",
success:function(html){
$("#name").val(html.data.name);
$("#email").val(html.data.email);
$("#phone").val(html.data.phone);
$("#id").val(html.data.id);
$(".modal-title").text("Update User Record");
$("#btn").val('Update User Record');
$("#new-form").modal("show");
}
});
});
$(".delete-button").click(function(){
record_id = $(this).attr('id');
$(".done-button").css("display", "block");
$(".modal-title").text("Confirmation");
$(".modal-body").html("Are you sure you want to delete this Record");
$("#new-form").modal("show");
});
$('.done-button').click(function(){
window.location.href = "{{ url('/') }}/form/destroy/"+record_id;
});
});
</script>
</body>
</html>

In this code of file you can the code of the form and you can also see the list of some jquery actions which we perform for thee Laravel Ajax CRUD. Now I can share the controller file which we use for this.

app/Http/Controllers/LaravelAjaxCrudController.php



namespace App\Http\Controllers;

use App\LaravelAjaxCrud;
use Illuminate\Http\Request;
use Validator;
class LaravelAjaxCrudController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = LaravelAjaxCrud::all()->sortByDesc('created_at');
        return view('index')->with('data', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validation = array(
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required'
        );
        $error = Validator::make($request->all(), $validation);
        if($error->fails())
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }

        $new_form = new LaravelAjaxCrud;
        $new_form->name = $request->name;
        $new_form->email = $request->email;
        $new_form->phone = $request->phone;

        $new_form->save();

        return response()->json(['success' => 'Data Inserted Successfully']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\LaravelAjaxCrud  $laravelAjaxCrud
     * @return \Illuminate\Http\Response
     */
    public function show(LaravelAjaxCrud $laravelAjaxCrud)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\LaravelAjaxCrud  $laravelAjaxCrud
     * @return \Illuminate\Http\Response
     */
    public function edit($id, Request $request)
    {
        if($request->ajax())
        {
            $data = LaravelAjaxCrud::findOrFail($id);
            return response()->json(['data' => $data]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\LaravelAjaxCrud  $laravelAjaxCrud
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $validation = array(
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required'
        );
        $error = Validator::make($request->all(), $validation);
        if($error->fails())
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }

        $update_form = LaravelAjaxCrud::where('id', $request->id)->first();
        $update_form->name = $request->name;
        $update_form->email = $request->email;
        $update_form->phone = $request->phone;

        $update_form->save();

        return response()->json(['success' => 'Data Update Successfully']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\LaravelAjaxCrud  $laravelAjaxCrud
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request,$id)
    {
        LaravelAjaxCrud::where('id', $id)->delete();
        return back()->with('success', 'Record Deletd Successfully');
    }
}

After that, I can share the web.php file

routes/web.php


/*
|--------------------------------------------------------------------------
| 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::resource('/form','LaravelAjaxCrudController');
Route::post('form/update', 'LaravelAjaxCrudController@update')->name('form.update');
Route::get('form/destroy/{id}', 'LaravelAjaxCrudController@destroy');

 

Share This Post :

Comments

There is no Comment Available for This Post

Add Comment

Request a Call Back

Get a free quote for your Business and we’ll get back to you as soon

web design dubai whatsapp number
web design dubai whatsapp number