Laravel 5 CRUD using AJAX & Modals + Bootstrap Template in Laravel 5.3

Laravel 5 Tutorial : how to create ajax crud, laravel 5 CRUD operations using Ajax and Modals with Bootstrap template. Download source code Ajax CRUD using Laravel 5.3

Laravel 5.3 tutorials - How to create simple CRUD example operations in Laravel 5.3 using Ajax and Modals? this lesson will show you how to perform CRUD operations using ajax in laravel 5.

At the previews tutorial, we have learn how to make simple CRUD in laravel, but that not using Ajax, please read Simple CRUD operations with Resource Controllers and How to create simple blog using Laravel 5.3

Laravel 5 CRUD using AJAX & Modals + Bootstrap Template in Laravel 5.3

Laravel 5 CRUD using AJAX

C.R.U.D Example with Ajax and Modals

Step 1 - we need to create new database, please create new database and named with "laravel_ajax_crud".

Create New Project (CRUD project)

Using composer, we will create new laravel project, and named it with "laravelajaxcrud".

cd c:\server\htdocs
....
composer create-project --prefer-dist laravel/laravel laravelajaxcrud

Connection Settings

In .ENV file, we will declare our connection to database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_ajax_crud
DB_USERNAME=root
DB_PASSWORD=ganteng666

Migrations

using Artisan Command, we will create new Migration.

php artisan make:migration create_blog_post_table

In your migration file, that stored on database\migrations\2016_10_18_215831_create_blog_post_table.php

public function up()
    {
      Schema::create('blog_post', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->string('description');
      $table->timestamps();
      });
    }

Create Models

using Artisan command, we need to create new model, and named it with "Blog", that will stored on App\Blog.php

php artisan make:model Blog

Blog.php Model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
    protected $table ='blog_post';
}

Create Views.

Under views folder, we will create new file (app.blade.php), that used for our template master and Ajax CRUD operations.

Laravel 5 ajax crud

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Simple CRUD with Ajax and Modal</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div class="container">
      @yield('content')
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    // Edit Data (Modal and function edit data)
    $(document).on('click', '.edit-modal', function() {
    $('#footer_action_button').text(" Update");
    $('#footer_action_button').addClass('glyphicon-check');
    $('#footer_action_button').removeClass('glyphicon-trash');
    $('.actionBtn').addClass('btn-success');
    $('.actionBtn').removeClass('btn-danger');
    $('.actionBtn').addClass('edit');
    $('.modal-title').text('Edit');
    $('.deleteContent').hide();
    $('.form-horizontal').show();
    $('#fid').val($(this).data('id'));
    $('#t').val($(this).data('title'));
    $('#d').val($(this).data('description'));
    $('#myModal').modal('show');
});
  $('.modal-footer').on('click', '.edit', function() {
  $.ajax({
      type: 'post',
      url: '/editItem',
      data: {
          '_token': $('input[name=_token]').val(),
          'id': $("#fid").val(),
          'title': $('#t').val(),
          'description': $('#d').val()
      },
      success: function(data) {
          $('.item' + data.id).replaceWith("<tr class='item" + data.id + "'><td>" + data.id + "</td><td>" + data.title + "</td><td>" + data.description + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-title='" + data.title + "' data-description='" + data.description + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-title='" + data.title + "' data-description='" + data.description + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
      }
  });
});
// add function
$("#add").click(function() {
  $.ajax({
    type: 'post',
    url: '/addItem',
    data: {
      '_token': $('input[name=_token]').val(),
      'title': $('input[name=title]').val(),
      'description': $('input[name=description]').val()
    },
    success: function(data) {
      if ((data.errors)) {
        $('.error').removeClass('hidden');
        $('.error').text(data.errors.title);
        $('.error').text(data.errors.description);
      } else {
        $('.error').remove();
        $('#table').append("<tr class='item" + data.id + "'><td>" + data.id + "</td><td>" + data.title + "</td><td>" + data.description + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-title='" + data.title + "' data-description='" + data.description + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-title='" + data.title + "' data-description='" + data.description + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
      }
    },
  });
  $('#title').val('');
  $('#description').val('');
});

//delete function
$(document).on('click', '.delete-modal', function() {
  $('#footer_action_button').text(" Delete");
  $('#footer_action_button').removeClass('glyphicon-check');
  $('#footer_action_button').addClass('glyphicon-trash');
  $('.actionBtn').removeClass('btn-success');
  $('.actionBtn').addClass('btn-danger');
  $('.actionBtn').addClass('delete');
  $('.modal-title').text('Delete');
  $('.id').text($(this).data('id'));
  $('.deleteContent').show();
  $('.form-horizontal').hide();
  $('.title').html($(this).data('title'));
  $('#myModal').modal('show');
});

$('.modal-footer').on('click', '.delete', function() {
  $.ajax({
    type: 'post',
    url: '/deleteItem',
    data: {
      '_token': $('input[name=_token]').val(),
      'id': $('.id').text()
    },
    success: function(data) {
      $('.item' + $('.id').text()).remove();
    }
  });
});

</script>
  </body>
</html>

Next, we will create new folder named with "blog" folder that stored under views folder resources\views\blog, Next, please create new page that using for CRUD operations page and named it with "index.blade.php"

resources\views\blog\index.blade.php

@extends('app')
  @section('content')

  <div class="row">
    <div class="col-md-12">
      <h1>Simple Laravel Ajax Crud</h1>
    </div>
  </div>

  <div class="form-group row add">
    <div class="col-md-5">
      <input type="text" class="form-control" id="title" name="title"
      placeholder="Your title Here" required>
      <p class="error text-center alert alert-danger hidden"></p>
    </div>
    <div class="col-md-5">
      <input type="text" class="form-control" id="description" name="description"
      placeholder="Your description Here" required>
      <p class="error text-center alert alert-danger hidden"></p>
    </div>
    <div class="col-md-2">
      <button class="btn btn-warning" type="submit" id="add">
        <span class="glyphicon glyphicon-plus"></span> Add New Data
      </button>
    </div>
  </div>

  <div class="row">
    <div class="table-responsive">
      <table class="table table-borderless" id="table">
        <tr>
          <th>No.</th>
          <th>Title</th>
          <th>Description</th>
          <th>Actions</th>
        </tr>
        {{ csrf_field() }}

        <?php $no=1; ?>
        @foreach($blogs as $blog)
          <tr class="item{{$blog->id}}">
            <td>{{$no++}}</td>
            <td>{{$blog->title}}</td>
            <td>{{$blog->description}}</td>
            <td>
            <button class="edit-modal btn btn-primary" data-id="{{$blog->id}}" data-title="{{$blog->title}}" data-description="{{$blog->description}}">
              <span class="glyphicon glyphicon-edit"></span> Edit
            </button>
            <button class="delete-modal btn btn-danger" data-id="{{$blog->id}}" data-title="{{$blog->title}}" data-description="{{$blog->description}}">
              <span class="glyphicon glyphicon-trash"></span> Delete
            </button>
          </td>
          </tr>
        @endforeach
      </table>
    </div>
  </div>
  <div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal" role="form">
            <div class="form-group">
              <label class="control-label col-sm-2" for="id">ID :</label>
              <div class="col-sm-10">
                <input type="text" class="form-control" id="fid" disabled>
              </div>
              </div>
              <div class="form-group">
              <label class="control-label col-sm-2" for="title">Title:</label>
              <div class="col-sm-10">
                <input type="name" class="form-control" id="t">
              </div>
            </div>
            <div class="form-group">
            <label class="control-label col-sm-2" for="description">Description:</label>
            <div class="col-sm-10">
              <input type="name" class="form-control" id="d">
            </div>
          </div>
          </form>
            <div class="deleteContent">
            Are you Sure you want to delete <span class="title"></span> ?
            <span class="hidden id"></span>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn actionBtn" data-dismiss="modal">
              <span id="footer_action_button" class='glyphicon'> </span>
            </button>
            <button type="button" class="btn btn-warning" data-dismiss="modal">
              <span class='glyphicon glyphicon-remove'></span> Close
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  @stop

Create new Controller (BlogController.php)

using Artisan command, we will create new controller.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Blog;
use Validator;
use Response;
use Illuminate\Support\Facades\Input;
class BlogController extends Controller
{
    public function index(){
      // we need to show all data from "blog" table
      $blogs = Blog::all();
      // show data to our view
      return view('blog.index',['blogs' => $blogs]);
    }

      // edit data function
      public function editItem(Request $req) {
      $blog = Blog::find ($req->id);
      $blog->title = $req->title;
      $blog->description = $req->description;
      $blog->save();
      return response()->json($blog);
    }

    // add data into database
    public function addItem(Request $req) {
      $rules = array(
        'title' => 'required',
        'description' => 'required'
      );
      // for Validator
      $validator = Validator::make ( Input::all (), $rules );
      if ($validator->fails())
      return Response::json(array('errors' => $validator->getMessageBag()->toArray()));

      else {
        $blog = new Blog();
        $blog->title = $req->title;
        $blog->description = $req->description;
        $blog->save();
        return response()->json($blog);
      }
    }
    // delete item
    public function deleteItem(Request $req) {
      Blog::find($req->id)->delete();
      return response()->json();
    }
}

Routes (web.php)

Route::get('/', function () {
    return view('welcome');
});
Route::group(['middleware' => ['web']], function() {
  Route::resource('blog','BlogController');
  Route::post ( '/editItem', 'BlogController@editItem' );
  Route::post ( '/addItem', 'BlogController@addItem' );
  Route::post ( '/deleteItem', 'BlogController@deleteItem' );
});

Video Ajax + Modals CRUD Example using Bootstrap template


Laravel 5.3 CRUD with VueJS


Video Tutorial Laravel CRUD with Angular Js


Download Full source code Laravel 5.3  Ajax CRUD Operations here >> https://goo.gl/Nc9h1S
See you next lessons ..

COMMENTS

Next Recomended


Feel free to code it up and send us a pull request.

Hi everyone, let's me know how much this lesson can help your work. Please Subscribe and Follow Our Social Media 'kodeajaib[dot]com' to get Latest tutorials and will be send to your email everyday for free!, Just hit a comment if you have confused. Nice to meet you and Happy coding :) all ^^



Follow by E-Mail


Name

ADO.NET,3,Ajax,6,Android,9,AngularJS,4,ASP.NET,4,Blogger Tutorials,7,Bootstrap,7,C++,1,Codeigniter,2,Cplusplus,6,Crystal Report,6,CSharp,25,Ebook Java,2,FlyExam,1,FSharp,3,Game Development,2,Java,35,JDBC,2,Laravel,84,Lumen,2,MariaDB,2,Ms Access,3,MySQL,31,ODBC,6,OleDB,1,PHP,14,PHP Framework,5,PHP MYSQLI,9,PHP OOP,5,Python,8,Python 3,4,SQL Server,4,SQLite,4,Uncategorized,5,Vb 6,2,Vb.Net,89,Video,48,Vue Js,4,WPF,2,Yii,3,
ltr
item
KODE AJAIB: Laravel 5 CRUD using AJAX & Modals + Bootstrap Template in Laravel 5.3
Laravel 5 CRUD using AJAX & Modals + Bootstrap Template in Laravel 5.3
Laravel 5 Tutorial : how to create ajax crud, laravel 5 CRUD operations using Ajax and Modals with Bootstrap template. Download source code Ajax CRUD using Laravel 5.3
https://3.bp.blogspot.com/-lk2YZdxptvk/WAev8nAc4GI/AAAAAAAACu8/YPcnVRABL7ozTAp13q0N3y1I24rkAOLOgCLcB/s320/laravel5-tutorial-ajax-modal-crud-operations.png
https://3.bp.blogspot.com/-lk2YZdxptvk/WAev8nAc4GI/AAAAAAAACu8/YPcnVRABL7ozTAp13q0N3y1I24rkAOLOgCLcB/s72-c/laravel5-tutorial-ajax-modal-crud-operations.png
KODE AJAIB
https://www.kodeajaib.com/2016/10/laravel-5-crud-using-ajax-modals.html
https://www.kodeajaib.com/
https://www.kodeajaib.com/
https://www.kodeajaib.com/2016/10/laravel-5-crud-using-ajax-modals.html
true
3214704946184383982
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy