Simple Laravel 5 Vue JS Ajax CRUD(insert update delete)

Today, We want to share with you Simple Laravel 5 Vue JS Ajax CRUD(insert update delete) Example and demo from scratch.In this post we will show you AJAX CRUD Tutorial Using vuejs, JSON and Laravel – Step by Step, hear for Laravel 5 and Vue JS CRUD with Pagination we will give you demo and example for implement.In this post, we will learn about Laravel 5 and Vue JS CRUD with Pagination example and demo from scratch with an example.

List of all Google Adsense, VueJS, AngularJS, PHP, Laravel Examples.

Simple Laravel 5 Vue JS Ajax CRUD(insert update delete)

There are the Following The simple About Simple Laravel 5 Vue JS Ajax CRUD(insert update delete) Example and demo from scratch Full Information With Example and source code.

As I will cover this Post with live Working example to develop Laravel MySQL CRUD Operations using vue js and Bootstrap, so the some major files and Directory structures for this example is following below.

  • Setup Laravel and Vuejs
  • Laravel Database and model
  • Laravel Route and Controller
  • Laravel view files
  • 1. Member Listing
  • 2. Member Create
  • 3. Member Edit
  • 4. Member Delete

Step 1: Setup Laravel and Vuejs

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

Step 2: Make members Database table and model

php artisan make:migration create_members_table

database/migrations
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMembersTable extends Migration
{
    public function up()
    {
        Schema::create('members', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('information');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::drop("members");
    }
}

app/Member.php

namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
    public $fillable = ['title','information'];
}

Step 3: Include Laravel Route and Controller

app/Http/routes.php

Route::get('manage-vue', '[email protected]');

Route::resource('vuemembers','VueMemberController');

app/Http/Controllers/VueMemberController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Member;
class VueMemberController extends Controller
{
    public function manageVue()
    {
        return view('manage-vue');
    }
    public function index(Request $request)
    {
        $members = Member::latest()->paginate(5);
        $response = [
            'pagination' => [
                'total' => $members->total(),
                'per_page' => $members->perPage(),
                'current_page' => $members->currentPage(),
                'last_page' => $members->lastPage(),
                'from' => $members->firstMember(),
                'to' => $members->lastMember()
            ],
            'data' => $members
        ];
        return response()->json($response);
    }
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'information' => 'required',
        ]);
        $create = Member::create($request->all());
        return response()->json($create);
    }
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required',
            'information' => 'required',
        ]);
        $edit = Member::find($id)->update($request->all());
        return response()->json($edit);
    }
    public function destroy($id)
    {
        Member::find($id)->delete();
        return response()->json(['done']);
    }
}

Step 4: Make Laravel view Blade File

resources/views/manage-vue.blade.php

<!DOCTYPE html>
<html>
<head>
	<title>Simple Laravel 5 Vue JS Ajax CRUD(insert update delete) tutorial example with source code</title>
	<meta id="token" name="token" value="{{ csrf_token() }}">
	<link rel="stylesheet" type="text/css" href="/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
</head>
<body>
	<div class="container" id="manage-vue">
		<div class="row">
		    <div class="col-lg-12 margin-tb">
		        <div class="pull-left">
		            <h2>Laravel Vue JS Member CRUD</h2>
		        </div>
		        <div class="pull-right">
				<button type="button" class="btn btn-success" data-toggle="modal" data-target="#create-member">
				  Create Member
				</button>
		        </div>
		    </div>
		</div>
		<!-- Member Listing -->
		<table class="table table-bordered">
			<tr>
				<th>Title</th>
				<th>Description</th>
				<th width="200px">Action</th>
			</tr>
			<tr v-for="member in members">
				<td>@{{ member.title }}</td>
				<td>@{{ member.information }}</td>
				<td>	
			      <button class="btn btn-primary" @click.prevent="editMember(member)">Edit</button>
			      <button class="btn btn-danger" @click.prevent="deleteMember(member)">Delete</button>
				</td>
			</tr>
		</table>
		<!-- Pagination -->
		<nav>
	        <ul class="pagination">
	            <li v-if="pagination.current_page > 1">
	                <a href="#" aria-label="Previous"
	                   @click.prevent="changePage(pagination.current_page - 1)">
	                    <span aria-hidden="true">«</span>
	                </a>
	            </li>
	            <li v-for="page in pagesNumber"
	                v-bind:class="[ page == isActived ? 'active' : '']">
	                <a href="#"
	                   @click.prevent="changePage(page)">@{{ page }}</a>
	            </li>
	            <li v-if="pagination.current_page < pagination.last_page">
	                <a href="#" aria-label="Next"
	                   @click.prevent="changePage(pagination.current_page + 1)">
	                    <span aria-hidden="true">»</span>
	                </a>
	            </li>
	        </ul>
	    </nav>
	    <!-- Create Member Modal -->
		<div class="modal fade" id="create-member" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
		  <div class="modal-dialog" role="document">
		    <div class="modal-content">
		      <div class="modal-header">
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
		        <h4 class="modal-title" id="myModalLabel">Create Member</h4>
		      </div>
		      <div class="modal-body">
		      		<form method="POST" enctype="multipart/form-data" v-on:submit.prevent="createMember">
		      			<div class="form-group">
						<label for="title">Title:</label>
						<input type="text" name="title" class="form-control" v-model="newMember.title" />
						<span v-if="formErrors['title']" class="error text-danger">@{{ formErrors['title'] }}</span>
					</div>
					<div class="form-group">
						<label for="title">Description:</label>
						<textarea name="information" class="form-control" v-model="newMember.information"></textarea>
						<span v-if="formErrors['information']" class="error text-danger">@{{ formErrors['information'] }}</span>
					</div>
					<div class="form-group">
						<button type="submit" class="btn btn-success">Submit</button>
					</div>
		      		</form>
		        
		      </div>
		    </div>
		  </div>
		</div>
		<!-- Edit Member Modal -->
		<div class="modal fade" id="edit-member" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
		  <div class="modal-dialog" role="document">
		    <div class="modal-content">
		      <div class="modal-header">
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
		        <h4 class="modal-title" id="myModalLabel">Edit Member</h4>
		      </div>
		      <div class="modal-body">
		      		<form method="POST" enctype="multipart/form-data" v-on:submit.prevent="updateMember(fillMember.id)">
		      			<div class="form-group">
						<label for="title">Title:</label>
						<input type="text" name="title" class="form-control" v-model="fillMember.title" />
						<span v-if="livefrmErrUpdate['title']" class="error text-danger">@{{ livefrmErrUpdate['title'] }}</span>
					</div>
					<div class="form-group">
						<label for="title">Description:</label>
						<textarea name="information" class="form-control" v-model="fillMember.information"></textarea>
						<span v-if="livefrmErrUpdate['information']" class="error text-danger">@{{ livefrmErrUpdate['information'] }}</span>
					</div>
					<div class="form-group">
						<button type="submit" class="btn btn-success">Submit</button>
					</div>
		      		</form>
		      </div>
		    </div>
		  </div>
		</div>
	</div>
	<script type="text/javascript" src="libs/jquery/3.1.0/jquery.min.js"></script>
	<script type="text/javascript" src="twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>
	<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
        <link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">
	<script type="text/javascript" src="libs/vue/1.0.26/vue.min.js"></script>
	<script type="text/javascript" src="vue.resource/0.9.3/vue-resource.min.js"></script>
	<script type="text/javascript" src="/js/member.js"></script>
</body>
</html>

Step 5: Make Vue JS File

public/js/member.js

//Simple Laravel 5 Vue JS Ajax CRUD(insert update delete) tutorial example with source code
Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("value");
new Vue({
  el: '#manage-vue',
  data: {
    members: [],
    pagination: {
        total: 0, 
        per_page: 2,
        from: 1, 
        to: 0,
        current_page: 1
      },
    offset: 4,
    formErrors:{},
    livefrmErrUpdate:{},
    newMember : {'title':'','information':''},
    fillMember : {'title':'','information':'','id':''}
  },
  computed: {
        isActived: function () {
            return this.pagination.current_page;
        },
        pagesNumber: function () {
            if (!this.pagination.to) {
                return [];
            }
            var from = this.pagination.current_page - this.offset;
            if (from < 1) {
                from = 1;
            }
            var to = from + (this.offset * 2);
            if (to >= this.pagination.last_page) {
                to = this.pagination.last_page;
            }
            var pagesArray = [];
            while (from <= to) {
                pagesArray.push(from);
                from++;
            }
            return pagesArray;
        }
    },
  ready : function(){
  		this.getVueMembers(this.pagination.current_page);
  },
  methods : {
        getVueMembers: function(page){
          this.$http.get('/vuemembers?page='+page).then((response) => {
            this.$set('members', response.data.data.data);
            this.$set('pagination', response.data.pagination);
          });
        },
        createMember: function(){
		  var input = this.newMember;
		  this.$http.post('/vuemembers',input).then((response) => {
		    this.changePage(this.pagination.current_page);
			this.newMember = {'title':'','information':''};
			$("#create-member").modal('hide');
			toastr.success('Member Created Successfully.', 'Success Alert', {timeOut: 5000});
		  }, (response) => {
			this.formErrors = response.data;
	    });
	},
      deleteMember: function(member){
        this.$http.delete('/vuemembers/'+member.id).then((response) => {
            this.changePage(this.pagination.current_page);
            toastr.success('Member Deleted Successfully.', 'Success Alert', {timeOut: 5000});
        });
      },
      editMember: function(member){
          this.fillMember.title = member.title;
          this.fillMember.id = member.id;
          this.fillMember.information = member.information;
          $("#edit-member").modal('show');
      },
      updateMember: function(id){
        var input = this.fillMember;
        this.$http.put('/vuemembers/'+id,input).then((response) => {
            this.changePage(this.pagination.current_page);
            this.fillMember = {'title':'','information':'','id':''};
            $("#edit-member").modal('hide');
            toastr.success('Member Updated Successfully.', 'Success Alert', {timeOut: 5000});
          }, (response) => {
              this.livefrmErrUpdate = response.data;
          });
      },
      changePage: function (page) {
          this.pagination.current_page = page;
          this.getVueMembers(page);
      }
  }
});

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Simple Laravel 5 Vue JS Ajax CRUD(insert update delete) tutorial example with source code.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Laravel 5/6/7 Import & Export data to Excel CSV using maatwebsite
  2.   laravel Add cascade on delete (ON DELETE CASCADE)
  3.   VueJS Hello World First Application
  4.   Create Animated Scroll To Top Button using jQuery
  5.   laravel checking if record exists
  6.   Laravel INSERT Multiple Rows Into a Table
  7.   Laravel Eloquent Get Last Inserted Id
  8.   Remove Special Characters from String using C#
  9.   Stripe API Upgrading and Downgrading Plans - Switching plans
  10.   Laravel 5/6/7 create custom facade

Leave a Reply

Your email address will not be published. Required fields are marked *