Laravel CRUD Series: Fetching Data using AJAX

Getting Started

First, I'm going to create a new project named mysite and add this to my localhost with the name mysite.dev. If you have no idea how to do this, please refer to my tutorial Installing Laravel.

Creating and Connecting our Database

In your phpMyAdmin, create a new database. In my case, I've create a database named mysite. In yourproject, in my case mysite, open .env file. Edit the ff lines with you database, username and password: DB_DATABASE=mysite DB_USERNAME=root DB_PASSWORD=

Creating our Controller and Model

Next, we're going to create our controller and model. To do this, open your command prompt, navigate to the project that you have created and type the ff codes: For Controller type: php artisan make:controller MemberController This code will create our controller in the form of MemberController.php file located in youproject/app/Http/Controller. Open this file and change it with the following codes:
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6. use App\Member;
  7.  
  8. class MemberController extends Controller
  9. {
  10.     public function index(){
  11.         return view('show');
  12.     }
  13.  
  14.     public function getMembers(){
  15.         $members = Member::all();
  16.  
  17.         return view('memberlist', compact('members'));
  18.     }
  19.  
  20. }
For Model type: php artisan make:model Member -m This will create our model in the form of Member.php file located in yourproject/app. Open the file and edit it with the following codes:
  1. <?php
  2.  
  3. namespace App;
  4.  
  5. use Illuminate\Database\Eloquent\Model;
  6.  
  7. class Member extends Model
  8. {
  9.     protected $table = 'members';
  10. }
Notice that we put -m when we create our model. This will automatically make the migration for our model and you will see that in yourproject/database/migrations, there is a file that has been created for our model. In my case, the file name is 2017_11_10_030339_create_members_table.php. Open this file and edit it with the ff codes:
  1. <?php
  2.  
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6.  
  7. class CreateMembersTable extends Migration
  8. {
  9.     /**
  10.      * Run the migrations.
  11.      *
  12.      * @return void
  13.      */
  14.     public function up()
  15.     {
  16.         Schema::create('members', function (Blueprint $table) {
  17.             $table->increments('id');
  18.             $table->string('firstname');
  19.             $table->string('lastname');
  20.             $table->timestamps();
  21.         });
  22.     }
  23.  
  24.     /**
  25.      * Reverse the migrations.
  26.      *
  27.      * @return void
  28.      */
  29.     public function down()
  30.     {
  31.         Schema::dropIfExists('members');
  32.     }
  33. }
This file is our table structure when we migrate.

Making our Database Migration

In command prompt, navigate to your project and type: php artisan migrate. This will create our table. If you have an error like this: [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t oo long; max key length is 767 bytes (SQL: alter table `users` add unique ` users_email_unique`(`email`)) You can solve this by opening AppServiceProvider.php located in yourproject/app/Providers. Add this line: use Illuminate\Support\Facades\Schema; In boot add this line: Schema::defaultStringLength(191); migrate error Run php artisan migrate again and make sure that your database is empty because it will have another error if its not.

Creating our Routes

In yourproject/routes, open web.php and edit it with the ff codes: Route::get('/', 'MemberController@index'); Route::get('/show', 'MemberController@getMembers');

Creating our Views

In yourproject/views, create the ff files: app.blade.php
  1. <!DOCTYPE html>
  2.         <meta charset="utf-8">
  3.         <meta name="csrf-token" content="{{ csrf_token() }}">
  4.         <title>Laravel Crud Operation</title>
  5.         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  6.         <link rel="stylesheet" href="/css/app.css">
  7.         <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  8.         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  9.         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  10. </head>
  11. <div class="container">
  12.         @yield('content')
  13. </div>
  14. @include('modal')
  15.  
  16. @yield('script')
  17. </body>
  18. </html>
memberlist.blade.php
  1. @foreach($members as $member)
  2.         <tr>
  3.                 <td>{{ $member->firstname }}</td>a
  4.                 <td>{{ $member->lastname }}</td>
  5.                 <td><a href='' class='btn btn-success' data-id='{{ $member->id }}'><i class='fa fa-edit'></i> Edit</a>
  6.                         <a href='' class='btn btn-danger' data-id='{{ $member->id }}'><i class='fa fa-trash'></i> Delete</a>
  7.                 </td>
  8.         </tr>
  9. @endforeach
show.blade.php
  1. @extends('app')
  2.  
  3. @section('content')
  4. <h1 class="page-header text-center">Laravel Crud Operation</h1>
  5. <div class="row">
  6.         <div class="col-md-10 col-md-offset-1">
  7.                 <h2>Members Table
  8.                         <button type="button" id="add" class="btn btn-primary pull-right"><i class="fa fa-plus"></i> Member</button>
  9.                 </h2>
  10.         </div>
  11. </div>
  12. <div class="row">
  13.         <div class="col-md-10 col-md-offset-1">
  14.                 <table class="table table-bordered table-responsive table-striped">
  15.                         <thead>
  16.                                 <th>Fisrtname</th>
  17.                                 <th>Lastname</th>
  18.                                 <th>Action</th>
  19.                         </thead>
  20.                         <tbody id="memberBody">
  21.                         </tbody>
  22.                 </table>
  23.         </div>
  24. </div>
  25. @endsection
  26.  
  27. @section('script')
  28.         <script type="text/javascript">
  29.                 $(document).ready(function(){
  30.                        
  31.                         showMember();
  32.  
  33.                         $('#add').click(function(){
  34.                                 $('#addnew').modal('show');
  35.                         });
  36.  
  37.                 });
  38.  
  39.                 function showMember(){
  40.                         $.get("{{ URL::to('show') }}", function(data){
  41.                         $('#memberBody').empty().html(data);
  42.                        
  43.                         })
  44.                 }
  45.         </script>
  46. @endsection
modal.blade.php Just created this file and leave it empty for now because where going to use this in the next tutorial.

Running the Server

In your web browser, type the localhost name of your project, in my case mysite.dev Add sample data in your phpMyAdmin manually for now and you should be able to view our table. fetching data laravel That ends this tutorial. Happy Coding :)

Add new comment