Laravel CRUD Series: Fetching Data using AJAX

Submitted by: 
Language: 
Visitors have accessed this post 307 times.

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:

  1. DB_DATABASE=mysite
  2. DB_USERNAME=root
  3. 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:

  1. Route::get('/', '<a href="mailto:[email protected]" rel="nofollow">[email protected]</a>');
  2.  
  3. Route::get('/show', '<a href="mailto:[email protected]" rel="nofollow">[email protected]</a>');

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="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"" rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"</a> />
  6. <link rel="stylesheet" href="/css/app.css">
  7. <link href="<a href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"" rel="nofollow">https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min....</a> rel="stylesheet">
  8. <script src="<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  9. " rel="nofollow">https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></scri...</a> <script src="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  10. </head>
  11. <div" rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></s...</a> 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. <th>Fisrtname</th>
  16. <th>Lastname</th>
  17. <th>Action</th>
  18. </thead>
  19. <tbody id="memberBody">
  20. </tbody>
  21. </table>
  22. </div>
  23. </div>
  24. @endsection
  25.  
  26. @section('script')
  27. <script type="text/javascript">
  28. $(document).ready(function(){
  29.  
  30. showMember();
  31.  
  32. $('#add').click(function(){
  33. $('#addnew').modal('show');
  34. });
  35.  
  36. });
  37.  
  38. function showMember(){
  39. $.get("{{ URL::to('show') }}", function(data){
  40. $('#memberBody').empty().html(data);
  41.  
  42. })
  43. }
  44. </script>
  45. @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

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe>
  • You may insert videos with [video:URL]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.