Hiển thị các bài đăng có nhãn Vue Js. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn Vue Js. Hiển thị tất cả bài đăng

Thứ Bảy, 25 tháng 11, 2017

Laravel 5.5 & VUEJS 2 Advanced CRUD Tutorial with Example step by step


Laravel 5.5 and VueJS tutorial for beginner : this tutorial will show you how to create advanced CRUD operation using laravel 5.5 and VUEJS 2. at the previews lessons, we have already discuss more about CRUD Apps using laravel, just read :
  1. Laravel 5.5 CRUD with resource Controller
  2. Laravel 5.3 & Angular JS CRUD Example
  3. Laravel 5.3 Ajax CRUD Example

Video Tutorial Laravel 5.5 & Vue JS CRUD Example



Full Source Code Laravel 5.5 & VueJS 2 CRUD Operations

Create new Laravel Project

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

Create new Migration

php artisan make:migration create_posts_table

Post Migration

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });

Create new Model and new Controller

php artisan make:model Post

php artisan make:controller PostController --resource

Post Model

protected $table = 'posts';
protected $fillable = ['title','body'];

PostController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppPost;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */

    public function home(){
      return view('vueApp');
    }

    public function index()
    {
        return Post::orderBy('id','DESC')->get();
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        $this->validate($request, [
          'title' => 'required',
          'body' => 'required',
        ]);

        $create = Post::create($request->all());
        return response()->json(['status' => 'success','msg'=>'post created successfully']);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function show($id)
    {
        return Post::find($id);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function edit($id)
    {
        return Post::find($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, $id)
    {
      $this->validate($request, [
        'title' => 'required',
        'body' => 'required',
      ]);

      $post = Post::find($id);
      if($post->count()){
        $post->update($request->all());
        return response()->json(['statur'=>'success','msg'=>'Post updated successfully']);
      } else {
        return response()->json(['statur'=>'error','msg'=>'error in updating post']);
      }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        $post = Post::find($id);
        if($post->count()){
          $post->delete();
          return response()->json(['statur'=>'success','msg'=>'Post deleted successfully']);
        } else {
          return response()->json(['statur'=>'error','msg'=>'error in deleting post']);
        }
    }
}

Route

Route::get('/', 'PostController@home');
Route::resource('/posts','PostController');

vueApp.blade.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <!-- CSRF Token -->
 <meta name="csrf-token" content="{{ csrf_token() }}">
 <title>{{ config('app.name', 'Laravel') }}</title>
 <!-- Styles -->
 <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">

 {{-- <link href="{{ asset('css/app.css') }}" rel="stylesheet"> --}}
</head>
<body>
<div class="container">
 <h3>Vue.js CRUD With Laravel 5.5 application</h3>
</div>

<section id="app"></section>

<script>
 window.Laravel = <?php echo json_encode([
 'csrfToken' => csrf_token(),
 ]); ?>
</script>

 <script src="{{ asset('js/app.js') }}"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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>
</body>
</html>

Installing Vue dependencies Run below command to install Vue js and bootstrap Frontend dependencies

npm install

Install vue-router by running below command for Vue js routing

npm install vue-router


Install vue-axios by running below command for Vue js api calls

npm install vue-axios

Once the dependencies of have been installed using npm install, you can compile your SASS files to plain CSS using Laravel Mix. Run npm run dev command on the terminal to process the instructions written in your webpack.mix.js file. npm run dev command will process the instruction written in webpack.mix.js file and place your compiled CSS and js in public/css and public/js directory.

npm run dev

npm run watch

Configuring Vue.js App and initializing Modules.

By default VueJS installations, we have app.js already in our project, next we will create more template page in resources\assets\js\components.
  1. Addposts.vue
  2. App.vue
  3. Deletepost.vue
  4. Editpost.vue
  5. Listpost.vue
  6. Viewpost.vue
and here's full source code of VueJS

app.js

require('./bootstrap');

window.Vue = require('vue');

window.VueRouter=require('vue-router').default;

window.VueAxios=require('vue-axios').default;

window.Axios=require('axios').default;

let AppLayout= require('./components/App.vue');

// show the list post template
const Listposts=Vue.component('Listposts', require('./components/Listposts.vue'));

// add post template
const Addpost =Vue.component('Addpost', require('./components/Addpost.vue'));

// edite post template
const Editpost =Vue.component('Editpost', require('./components/Editpost.vue'));

// delete post template
const Deletepost =Vue.component('Deletepost', require('./components/Deletepost.vue'));

// view single post template
const Viewpost =Vue.component('Viewpost', require('./components/Viewpost.vue'));

// registering Modules
Vue.use(VueRouter,VueAxios, axios);

const routes = [
  {
    name: 'Listposts',
    path: '/',
    component: Listposts
  },
  {
    name: 'Addpost',
    path: '/add-post',
    component: Addpost
  },
  {
    name: 'Editpost',
    path: '/edit/:id',
    component: Editpost
  },
  {
    name: 'Deletepost',
    path: '/post-delete',
    component: Deletepost
  },
  {
    name: 'Viewpost',
    path: '/view/:id',
    component: Viewpost
  }
];

const router = new VueRouter({ mode: 'history', routes: routes});

new Vue(
 Vue.util.extend(
 { router },
 AppLayout
 )
).$mount('#app');

Addpost.vue

<template id="add-post">
  <div>
    <h3>Add new Post</h3>
    <form v-on:submit.prevent = "createPost">
      <div class="form-group">
        <label for="add-title">Title</label>
        <input id="add-title" v-model="post.title" class="form-control" required />
      </div>
      <div class="form-group">
        <label for="add-body">Body</label>
        <textarea class="form-control" rows="10" v-model="post.body"></textarea>
      </div>
      <button type="submit" class="btn btn-xs btn-primary">Create Post</button>
      <router-link class="btn btn-xs btn-warning" v-bind:to="'/'">Cancel</router-link>
    </form>
  </div>
</template>

<script>
 export default {
   data: function () {
 return {post: {title: '', body: ''}}
 },
 methods: {
   createPost: function() {
     let uri = 'http://localhost:8000/posts/';
     Axios.post(uri, this.post).then((response) => {
     this.$router.push({name: 'Listposts'})
     })
   }
 }
 }
</script>

App.vue

<template>
 <div class="container">
 <transition name="fade">
 <router-view></router-view>
 </transition>
 </div>
</template>

<script>
export default {
 mounted() {
 console.log('Component mounted.')
 }
 }
</script>

Deletepost.vue

<template id="post-delete">
  <div>
    <h3>Delete post {{ post.title  }}</h3>
    <form v-on:submit.prevent = "deletePost">
      <p>The action cannot be undone</p>
      <button class="btn btn-xs btn-danger" type="submit" name="button">Delete</button>
      <router-link class="btn btn-xs btn-primary" v-bind:to="'/'">Back</router-link>
    </form>
  </div>
</template>

<script>
export default {
  data: function () {
  return {post: {body: '', title: ''}}
  },
  created: function(){
    let uri = 'http://localhost:8000/posts/'+this.$route.params.id+'/edit';
    Axios.get(uri).then((response) => {
    this.post = response.data;
    });
  },
  methods: {
    deletePost: function() {
    let uri = 'http://localhost:8000/posts/'+this.$route.params.id;
    Axios.delete(uri, this.post).then((response) => {
      this.$router.push({name: 'Listposts'})
    })
    }
  }
}
</script>

Editpost.vue

<template id="post-edit">
  <div>
    <h3>Add new Post</h3>
    <form v-on:submit.prevent = "updatePost">
      <div class="form-group">
        <label for="edit-title">Title</label>
        <input id="edit-title" v-model="post.title" class="form-control" required />
      </div>
      <div class="form-group">
        <label for="edit-body">Body</label>
        <textarea class="form-control" rows="10" v-model="post.body"></textarea>
      </div>
      <button type="submit" class="btn btn-xs btn-primary">Create Post</button>
      <router-link class="btn btn-xs btn-warning" v-bind:to="'/'">Cancel</router-link>
    </form>
  </div>
</template>

<script>
export default{
  data: function () {
    return {post: {title: '', body: ''}}
  },
  created: function(){
    let uri = 'http://localhost:8000/posts/'+this.$route.params.id+'/edit';
    Axios.get(uri).then((response) => {
    this.post = response.data;
  });
  },
  methods: {
    updatePost: function() {
      let uri = 'http://localhost:8000/posts/'+this.$route.params.id;
      Axios.patch(uri, this.post).then((response) => {
      this.$router.push({name: 'Listposts'})
    })
  }
  }
}
</script>

Listpost.vue

<template id="post-list">
  <div class="row">
    <div class="pull-right">
      <router-link class="btn btn-xs btn-primary" v-bind:to="{path: '/add-post'}">
        <span class="glyphicon glyphicon-plus"></span>
        Add new Post
      </router-link>
    </br></br>
    </div>
    <table class="table">
      <thead>
        <tr>
          <th>#</th>
          <th>Post Title</th>
          <th>Post Body</th>
          <th>Created At</th>
          <th>Updated At</th>
          <th class="col-md-2">Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(post, index) in filteredPosts">
          <td>{{ index + 1 }}</td>
          <td>{{ post.title }}</td>
          <td>{{ post.body }}</td>
          <td>{{ post.created_at }}</td>
          <td>{{ post.updated_at }}</td>
          <td>
            <router-link class="btn btn-info btn-xs" v-bind:to="{name: 'Viewpost', params: {id: post.id}}"><i class="fa fa-eye" aria-hidden="true"></i> Show</router-link>
            <router-link class="btn btn-warning btn-xs" v-bind:to="{name: 'Editpost', params: {id: post.id}}"><i class="fa fa-pencil" aria-hidden="true"></i> Edit</router-link>
            <router-link class="btn btn-danger btn-xs" v-bind:to="{name: 'Deletepost', params: {id: post.id}}"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete</router-link>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data:function(){
    return {posts: ''};
  },
  created: function() {
    let uri = 'http://localhost:8000/posts/';
    Axios.get(uri).then((response) => {
      this.posts = response.data;
    });
  },
  computed: {
    filteredPosts: function(){
      if(this.posts.length) {
        return this.posts;
      }
    }
  }
}
</script>

Viewpost.vue

<template id="post">
  <div>
    <h3>{{ post.title }}</h3>
    <strong>Body : </strong>
    <div>
      {{ post.body }}
    </div>
  </br>
  <span class="glyphicon glyphicon-arrow-left"></span>
  <router-link v-bind:to="'/'">Back to post list</router-link>
  </div>
</template>

<script>
   export default {
   data: function () {
   return {post: {title: '', body: ''}}
 },
 created: function(){
   let uri = 'http://localhost:8000/posts/'+this.$route.params.id;
     Axios.get(uri).then((response) => {
     this.post = response.data;
   });
 }
 }
</script>


More Laravel 5.5 Video Tutorial

Video tutorial  How to create CRUD Operations in Laravel 5.5









See you next Lessons ..

Laravel 5.5 & VUEJS 2 Advanced CRUD Tutorial with Example step by step


Laravel 5.5 and VueJS tutorial for beginner : this tutorial will show you how to create advanced CRUD operation using laravel 5.5 and VUEJS 2. at the previews lessons, we have already discuss more about CRUD Apps using laravel, just read :
  1. Laravel 5.5 CRUD with resource Controller
  2. Laravel 5.3 & Angular JS CRUD Example
  3. Laravel 5.3 Ajax CRUD Example

Video Tutorial Laravel 5.5 & Vue JS CRUD Example



Full Source Code Laravel 5.5 & VueJS 2 CRUD Operations

Create new Laravel Project

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

Create new Migration

php artisan make:migration create_posts_table

Post Migration

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });

Create new Model and new Controller

php artisan make:model Post

php artisan make:controller PostController --resource

Post Model

protected $table = 'posts';
protected $fillable = ['title','body'];

PostController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppPost;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */

    public function home(){
      return view('vueApp');
    }

    public function index()
    {
        return Post::orderBy('id','DESC')->get();
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        $this->validate($request, [
          'title' => 'required',
          'body' => 'required',
        ]);

        $create = Post::create($request->all());
        return response()->json(['status' => 'success','msg'=>'post created successfully']);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function show($id)
    {
        return Post::find($id);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function edit($id)
    {
        return Post::find($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, $id)
    {
      $this->validate($request, [
        'title' => 'required',
        'body' => 'required',
      ]);

      $post = Post::find($id);
      if($post->count()){
        $post->update($request->all());
        return response()->json(['statur'=>'success','msg'=>'Post updated successfully']);
      } else {
        return response()->json(['statur'=>'error','msg'=>'error in updating post']);
      }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        $post = Post::find($id);
        if($post->count()){
          $post->delete();
          return response()->json(['statur'=>'success','msg'=>'Post deleted successfully']);
        } else {
          return response()->json(['statur'=>'error','msg'=>'error in deleting post']);
        }
    }
}

Route

Route::get('/', 'PostController@home');
Route::resource('/posts','PostController');

vueApp.blade.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <!-- CSRF Token -->
 <meta name="csrf-token" content="{{ csrf_token() }}">
 <title>{{ config('app.name', 'Laravel') }}</title>
 <!-- Styles -->
 <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">

 {{-- <link href="{{ asset('css/app.css') }}" rel="stylesheet"> --}}
</head>
<body>
<div class="container">
 <h3>Vue.js CRUD With Laravel 5.5 application</h3>
</div>

<section id="app"></section>

<script>
 window.Laravel = <?php echo json_encode([
 'csrfToken' => csrf_token(),
 ]); ?>
</script>

 <script src="{{ asset('js/app.js') }}"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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>
</body>
</html>

Installing Vue dependencies Run below command to install Vue js and bootstrap Frontend dependencies

npm install

Install vue-router by running below command for Vue js routing

npm install vue-router


Install vue-axios by running below command for Vue js api calls

npm install vue-axios

Once the dependencies of have been installed using npm install, you can compile your SASS files to plain CSS using Laravel Mix. Run npm run dev command on the terminal to process the instructions written in your webpack.mix.js file. npm run dev command will process the instruction written in webpack.mix.js file and place your compiled CSS and js in public/css and public/js directory.

npm run dev

npm run watch

Configuring Vue.js App and initializing Modules.

By default VueJS installations, we have app.js already in our project, next we will create more template page in resources\assets\js\components.
  1. Addposts.vue
  2. App.vue
  3. Deletepost.vue
  4. Editpost.vue
  5. Listpost.vue
  6. Viewpost.vue
and here's full source code of VueJS

app.js

require('./bootstrap');

window.Vue = require('vue');

window.VueRouter=require('vue-router').default;

window.VueAxios=require('vue-axios').default;

window.Axios=require('axios').default;

let AppLayout= require('./components/App.vue');

// show the list post template
const Listposts=Vue.component('Listposts', require('./components/Listposts.vue'));

// add post template
const Addpost =Vue.component('Addpost', require('./components/Addpost.vue'));

// edite post template
const Editpost =Vue.component('Editpost', require('./components/Editpost.vue'));

// delete post template
const Deletepost =Vue.component('Deletepost', require('./components/Deletepost.vue'));

// view single post template
const Viewpost =Vue.component('Viewpost', require('./components/Viewpost.vue'));

// registering Modules
Vue.use(VueRouter,VueAxios, axios);

const routes = [
  {
    name: 'Listposts',
    path: '/',
    component: Listposts
  },
  {
    name: 'Addpost',
    path: '/add-post',
    component: Addpost
  },
  {
    name: 'Editpost',
    path: '/edit/:id',
    component: Editpost
  },
  {
    name: 'Deletepost',
    path: '/post-delete',
    component: Deletepost
  },
  {
    name: 'Viewpost',
    path: '/view/:id',
    component: Viewpost
  }
];

const router = new VueRouter({ mode: 'history', routes: routes});

new Vue(
 Vue.util.extend(
 { router },
 AppLayout
 )
).$mount('#app');

Addpost.vue

<template id="add-post">
  <div>
    <h3>Add new Post</h3>
    <form v-on:submit.prevent = "createPost">
      <div class="form-group">
        <label for="add-title">Title</label>
        <input id="add-title" v-model="post.title" class="form-control" required />
      </div>
      <div class="form-group">
        <label for="add-body">Body</label>
        <textarea class="form-control" rows="10" v-model="post.body"></textarea>
      </div>
      <button type="submit" class="btn btn-xs btn-primary">Create Post</button>
      <router-link class="btn btn-xs btn-warning" v-bind:to="'/'">Cancel</router-link>
    </form>
  </div>
</template>

<script>
 export default {
   data: function () {
 return {post: {title: '', body: ''}}
 },
 methods: {
   createPost: function() {
     let uri = 'http://localhost:8000/posts/';
     Axios.post(uri, this.post).then((response) => {
     this.$router.push({name: 'Listposts'})
     })
   }
 }
 }
</script>

App.vue

<template>
 <div class="container">
 <transition name="fade">
 <router-view></router-view>
 </transition>
 </div>
</template>

<script>
export default {
 mounted() {
 console.log('Component mounted.')
 }
 }
</script>

Deletepost.vue

<template id="post-delete">
  <div>
    <h3>Delete post {{ post.title  }}</h3>
    <form v-on:submit.prevent = "deletePost">
      <p>The action cannot be undone</p>
      <button class="btn btn-xs btn-danger" type="submit" name="button">Delete</button>
      <router-link class="btn btn-xs btn-primary" v-bind:to="'/'">Back</router-link>
    </form>
  </div>
</template>

<script>
export default {
  data: function () {
  return {post: {body: '', title: ''}}
  },
  created: function(){
    let uri = 'http://localhost:8000/posts/'+this.$route.params.id+'/edit';
    Axios.get(uri).then((response) => {
    this.post = response.data;
    });
  },
  methods: {
    deletePost: function() {
    let uri = 'http://localhost:8000/posts/'+this.$route.params.id;
    Axios.delete(uri, this.post).then((response) => {
      this.$router.push({name: 'Listposts'})
    })
    }
  }
}
</script>

Editpost.vue

<template id="post-edit">
  <div>
    <h3>Add new Post</h3>
    <form v-on:submit.prevent = "updatePost">
      <div class="form-group">
        <label for="edit-title">Title</label>
        <input id="edit-title" v-model="post.title" class="form-control" required />
      </div>
      <div class="form-group">
        <label for="edit-body">Body</label>
        <textarea class="form-control" rows="10" v-model="post.body"></textarea>
      </div>
      <button type="submit" class="btn btn-xs btn-primary">Create Post</button>
      <router-link class="btn btn-xs btn-warning" v-bind:to="'/'">Cancel</router-link>
    </form>
  </div>
</template>

<script>
export default{
  data: function () {
    return {post: {title: '', body: ''}}
  },
  created: function(){
    let uri = 'http://localhost:8000/posts/'+this.$route.params.id+'/edit';
    Axios.get(uri).then((response) => {
    this.post = response.data;
  });
  },
  methods: {
    updatePost: function() {
      let uri = 'http://localhost:8000/posts/'+this.$route.params.id;
      Axios.patch(uri, this.post).then((response) => {
      this.$router.push({name: 'Listposts'})
    })
  }
  }
}
</script>

Listpost.vue

<template id="post-list">
  <div class="row">
    <div class="pull-right">
      <router-link class="btn btn-xs btn-primary" v-bind:to="{path: '/add-post'}">
        <span class="glyphicon glyphicon-plus"></span>
        Add new Post
      </router-link>
    </br></br>
    </div>
    <table class="table">
      <thead>
        <tr>
          <th>#</th>
          <th>Post Title</th>
          <th>Post Body</th>
          <th>Created At</th>
          <th>Updated At</th>
          <th class="col-md-2">Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(post, index) in filteredPosts">
          <td>{{ index + 1 }}</td>
          <td>{{ post.title }}</td>
          <td>{{ post.body }}</td>
          <td>{{ post.created_at }}</td>
          <td>{{ post.updated_at }}</td>
          <td>
            <router-link class="btn btn-info btn-xs" v-bind:to="{name: 'Viewpost', params: {id: post.id}}"><i class="fa fa-eye" aria-hidden="true"></i> Show</router-link>
            <router-link class="btn btn-warning btn-xs" v-bind:to="{name: 'Editpost', params: {id: post.id}}"><i class="fa fa-pencil" aria-hidden="true"></i> Edit</router-link>
            <router-link class="btn btn-danger btn-xs" v-bind:to="{name: 'Deletepost', params: {id: post.id}}"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete</router-link>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data:function(){
    return {posts: ''};
  },
  created: function() {
    let uri = 'http://localhost:8000/posts/';
    Axios.get(uri).then((response) => {
      this.posts = response.data;
    });
  },
  computed: {
    filteredPosts: function(){
      if(this.posts.length) {
        return this.posts;
      }
    }
  }
}
</script>

Viewpost.vue

<template id="post">
  <div>
    <h3>{{ post.title }}</h3>
    <strong>Body : </strong>
    <div>
      {{ post.body }}
    </div>
  </br>
  <span class="glyphicon glyphicon-arrow-left"></span>
  <router-link v-bind:to="'/'">Back to post list</router-link>
  </div>
</template>

<script>
   export default {
   data: function () {
   return {post: {title: '', body: ''}}
 },
 created: function(){
   let uri = 'http://localhost:8000/posts/'+this.$route.params.id;
     Axios.get(uri).then((response) => {
     this.post = response.data;
   });
 }
 }
</script>


More Laravel 5.5 Video Tutorial

Video tutorial  How to create CRUD Operations in Laravel 5.5









See you next Lessons ..

Laravel 5.5 & VUEJS 2 Advanced CRUD Tutorial with Example step by step


Laravel 5.5 and VueJS tutorial for beginner : this tutorial will show you how to create advanced CRUD operation using laravel 5.5 and VUEJS 2. at the previews lessons, we have already discuss more about CRUD Apps using laravel, just read :
  1. Laravel 5.5 CRUD with resource Controller
  2. Laravel 5.3 & Angular JS CRUD Example
  3. Laravel 5.3 Ajax CRUD Example

Video Tutorial Laravel 5.5 & Vue JS CRUD Example



Full Source Code Laravel 5.5 & VueJS 2 CRUD Operations

Create new Laravel Project

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

Create new Migration

php artisan make:migration create_posts_table

Post Migration

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });

Create new Model and new Controller

php artisan make:model Post

php artisan make:controller PostController --resource

Post Model

protected $table = 'posts';
protected $fillable = ['title','body'];

PostController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppPost;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */

    public function home(){
      return view('vueApp');
    }

    public function index()
    {
        return Post::orderBy('id','DESC')->get();
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        $this->validate($request, [
          'title' => 'required',
          'body' => 'required',
        ]);

        $create = Post::create($request->all());
        return response()->json(['status' => 'success','msg'=>'post created successfully']);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function show($id)
    {
        return Post::find($id);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function edit($id)
    {
        return Post::find($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, $id)
    {
      $this->validate($request, [
        'title' => 'required',
        'body' => 'required',
      ]);

      $post = Post::find($id);
      if($post->count()){
        $post->update($request->all());
        return response()->json(['statur'=>'success','msg'=>'Post updated successfully']);
      } else {
        return response()->json(['statur'=>'error','msg'=>'error in updating post']);
      }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        $post = Post::find($id);
        if($post->count()){
          $post->delete();
          return response()->json(['statur'=>'success','msg'=>'Post deleted successfully']);
        } else {
          return response()->json(['statur'=>'error','msg'=>'error in deleting post']);
        }
    }
}

Route

Route::get('/', 'PostController@home');
Route::resource('/posts','PostController');

vueApp.blade.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <!-- CSRF Token -->
 <meta name="csrf-token" content="{{ csrf_token() }}">
 <title>{{ config('app.name', 'Laravel') }}</title>
 <!-- Styles -->
 <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">

 {{-- <link href="{{ asset('css/app.css') }}" rel="stylesheet"> --}}
</head>
<body>
<div class="container">
 <h3>Vue.js CRUD With Laravel 5.5 application</h3>
</div>

<section id="app"></section>

<script>
 window.Laravel = <?php echo json_encode([
 'csrfToken' => csrf_token(),
 ]); ?>
</script>

 <script src="{{ asset('js/app.js') }}"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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>
</body>
</html>

Installing Vue dependencies Run below command to install Vue js and bootstrap Frontend dependencies

npm install

Install vue-router by running below command for Vue js routing

npm install vue-router


Install vue-axios by running below command for Vue js api calls

npm install vue-axios

Once the dependencies of have been installed using npm install, you can compile your SASS files to plain CSS using Laravel Mix. Run npm run dev command on the terminal to process the instructions written in your webpack.mix.js file. npm run dev command will process the instruction written in webpack.mix.js file and place your compiled CSS and js in public/css and public/js directory.

npm run dev

npm run watch

Configuring Vue.js App and initializing Modules.

By default VueJS installations, we have app.js already in our project, next we will create more template page in resources\assets\js\components.
  1. Addposts.vue
  2. App.vue
  3. Deletepost.vue
  4. Editpost.vue
  5. Listpost.vue
  6. Viewpost.vue
and here's full source code of VueJS

app.js

require('./bootstrap');

window.Vue = require('vue');

window.VueRouter=require('vue-router').default;

window.VueAxios=require('vue-axios').default;

window.Axios=require('axios').default;

let AppLayout= require('./components/App.vue');

// show the list post template
const Listposts=Vue.component('Listposts', require('./components/Listposts.vue'));

// add post template
const Addpost =Vue.component('Addpost', require('./components/Addpost.vue'));

// edite post template
const Editpost =Vue.component('Editpost', require('./components/Editpost.vue'));

// delete post template
const Deletepost =Vue.component('Deletepost', require('./components/Deletepost.vue'));

// view single post template
const Viewpost =Vue.component('Viewpost', require('./components/Viewpost.vue'));

// registering Modules
Vue.use(VueRouter,VueAxios, axios);

const routes = [
  {
    name: 'Listposts',
    path: '/',
    component: Listposts
  },
  {
    name: 'Addpost',
    path: '/add-post',
    component: Addpost
  },
  {
    name: 'Editpost',
    path: '/edit/:id',
    component: Editpost
  },
  {
    name: 'Deletepost',
    path: '/post-delete',
    component: Deletepost
  },
  {
    name: 'Viewpost',
    path: '/view/:id',
    component: Viewpost
  }
];

const router = new VueRouter({ mode: 'history', routes: routes});

new Vue(
 Vue.util.extend(
 { router },
 AppLayout
 )
).$mount('#app');

Addpost.vue

<template id="add-post">
  <div>
    <h3>Add new Post</h3>
    <form v-on:submit.prevent = "createPost">
      <div class="form-group">
        <label for="add-title">Title</label>
        <input id="add-title" v-model="post.title" class="form-control" required />
      </div>
      <div class="form-group">
        <label for="add-body">Body</label>
        <textarea class="form-control" rows="10" v-model="post.body"></textarea>
      </div>
      <button type="submit" class="btn btn-xs btn-primary">Create Post</button>
      <router-link class="btn btn-xs btn-warning" v-bind:to="'/'">Cancel</router-link>
    </form>
  </div>
</template>

<script>
 export default {
   data: function () {
 return {post: {title: '', body: ''}}
 },
 methods: {
   createPost: function() {
     let uri = 'http://localhost:8000/posts/';
     Axios.post(uri, this.post).then((response) => {
     this.$router.push({name: 'Listposts'})
     })
   }
 }
 }
</script>

App.vue

<template>
 <div class="container">
 <transition name="fade">
 <router-view></router-view>
 </transition>
 </div>
</template>

<script>
export default {
 mounted() {
 console.log('Component mounted.')
 }
 }
</script>

Deletepost.vue

<template id="post-delete">
  <div>
    <h3>Delete post {{ post.title  }}</h3>
    <form v-on:submit.prevent = "deletePost">
      <p>The action cannot be undone</p>
      <button class="btn btn-xs btn-danger" type="submit" name="button">Delete</button>
      <router-link class="btn btn-xs btn-primary" v-bind:to="'/'">Back</router-link>
    </form>
  </div>
</template>

<script>
export default {
  data: function () {
  return {post: {body: '', title: ''}}
  },
  created: function(){
    let uri = 'http://localhost:8000/posts/'+this.$route.params.id+'/edit';
    Axios.get(uri).then((response) => {
    this.post = response.data;
    });
  },
  methods: {
    deletePost: function() {
    let uri = 'http://localhost:8000/posts/'+this.$route.params.id;
    Axios.delete(uri, this.post).then((response) => {
      this.$router.push({name: 'Listposts'})
    })
    }
  }
}
</script>

Editpost.vue

<template id="post-edit">
  <div>
    <h3>Add new Post</h3>
    <form v-on:submit.prevent = "updatePost">
      <div class="form-group">
        <label for="edit-title">Title</label>
        <input id="edit-title" v-model="post.title" class="form-control" required />
      </div>
      <div class="form-group">
        <label for="edit-body">Body</label>
        <textarea class="form-control" rows="10" v-model="post.body"></textarea>
      </div>
      <button type="submit" class="btn btn-xs btn-primary">Create Post</button>
      <router-link class="btn btn-xs btn-warning" v-bind:to="'/'">Cancel</router-link>
    </form>
  </div>
</template>

<script>
export default{
  data: function () {
    return {post: {title: '', body: ''}}
  },
  created: function(){
    let uri = 'http://localhost:8000/posts/'+this.$route.params.id+'/edit';
    Axios.get(uri).then((response) => {
    this.post = response.data;
  });
  },
  methods: {
    updatePost: function() {
      let uri = 'http://localhost:8000/posts/'+this.$route.params.id;
      Axios.patch(uri, this.post).then((response) => {
      this.$router.push({name: 'Listposts'})
    })
  }
  }
}
</script>

Listpost.vue

<template id="post-list">
  <div class="row">
    <div class="pull-right">
      <router-link class="btn btn-xs btn-primary" v-bind:to="{path: '/add-post'}">
        <span class="glyphicon glyphicon-plus"></span>
        Add new Post
      </router-link>
    </br></br>
    </div>
    <table class="table">
      <thead>
        <tr>
          <th>#</th>
          <th>Post Title</th>
          <th>Post Body</th>
          <th>Created At</th>
          <th>Updated At</th>
          <th class="col-md-2">Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(post, index) in filteredPosts">
          <td>{{ index + 1 }}</td>
          <td>{{ post.title }}</td>
          <td>{{ post.body }}</td>
          <td>{{ post.created_at }}</td>
          <td>{{ post.updated_at }}</td>
          <td>
            <router-link class="btn btn-info btn-xs" v-bind:to="{name: 'Viewpost', params: {id: post.id}}"><i class="fa fa-eye" aria-hidden="true"></i> Show</router-link>
            <router-link class="btn btn-warning btn-xs" v-bind:to="{name: 'Editpost', params: {id: post.id}}"><i class="fa fa-pencil" aria-hidden="true"></i> Edit</router-link>
            <router-link class="btn btn-danger btn-xs" v-bind:to="{name: 'Deletepost', params: {id: post.id}}"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete</router-link>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data:function(){
    return {posts: ''};
  },
  created: function() {
    let uri = 'http://localhost:8000/posts/';
    Axios.get(uri).then((response) => {
      this.posts = response.data;
    });
  },
  computed: {
    filteredPosts: function(){
      if(this.posts.length) {
        return this.posts;
      }
    }
  }
}
</script>

Viewpost.vue

<template id="post">
  <div>
    <h3>{{ post.title }}</h3>
    <strong>Body : </strong>
    <div>
      {{ post.body }}
    </div>
  </br>
  <span class="glyphicon glyphicon-arrow-left"></span>
  <router-link v-bind:to="'/'">Back to post list</router-link>
  </div>
</template>

<script>
   export default {
   data: function () {
   return {post: {title: '', body: ''}}
 },
 created: function(){
   let uri = 'http://localhost:8000/posts/'+this.$route.params.id;
     Axios.get(uri).then((response) => {
     this.post = response.data;
   });
 }
 }
</script>


More Laravel 5.5 Video Tutorial

Video tutorial  How to create CRUD Operations in Laravel 5.5









See you next Lessons ..

Thứ Sáu, 2 tháng 12, 2016

Laravel Scout and Vue.Js : How to create Search Function in Laravel 5.3


Laravel 5.3 tutorial : This lesson will show you how to create simple search function using Laravel Scout and Vue.Js, at the previews lessons we have learn how to build simple search using GET Method, please read Simple Search Function Using GET Method in laravel 5.3.

How to create Search Function in Laravel 5.3?

First, we will need laravel was installed on our server, if not, i assumed you to read and do step by step on this lessons How to build Blog using laravel step by step.

Video tutorial How to create Search Function in Laravel 5.3

Just watch this video, and follow step by step.


Routes (Web and Api)

web.php

Route::get('/','Api\SearchController@search');

api.php

Route::get('/search', 'Api\SearchController@search');

Api Controller (SearchController.php)

<?php
namespace App\Http\Controllers\Api;
use App\Posts;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SearchController extends Controller {
    // we will Installing and configuring Laravel Scout
    public function search(Request $req){
      // First we define the error message we are going to show if no keywords
      $error = ['error'=>'No results found'];
      // if the user entered the keyword
      if ($req->has('q')){
        // Using the Laravel Scout syntax to search the products table.
        $posts = Posts::search($req->get('q'))->get();
        // If there are results return them, if none, return the error message.
        return $posts->count() ? $posts : $error;
      } else {
        // we will show all posts data from database
        $posts = Posts::all();
        return view('search')->withPosts($posts);
      }
    }
}

Search.blade.php

<!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 Vue.Js Search Function</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">
      <div class="row" id="posts">
        <div class="col-md-12">
          <div class="input-group input-group-sm">
            <div class="icon-addon addon-md">
              <input type="text" v-model="query" placeholder="What are you looking for?" class="form-control">
            </div>
            <span class="input-group-btn">
              <button type="button" class="btn-sm btn-danger" v-if="!loading" @click="search()">
                Search <i class="fa fa-search"></i>
              </button>
              <button type="button" class="btn-sm btn-danger" v-if="loading" disabled="disabled">
                Searching... <i class="fa fa-search"></i>
              </button>
            </span>
          </div>
        </div>

        <div class="row">
          <div class="col-md-12">
            <div class="post-preview" v-for="post in posts">
              <p>
                <span class="well-sm"><strong>
                  <a href="#">@{{ post.title }}</a>
                </strong>
                </span>
                <span class="alert-danger">
                  On @{{ post.created_at }}
                </span>
              </p>
            </div>
          </div>
        </div>
      </div>
      <!-- Show all data posts from database -->
      <div class="row">
        <div class="col-md-12">
          <div class="post-preview">
            <div class="alert alert-warning" v-if="noresult">
              <h2><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                @{{ noresult }}
              </h2>
              <span class="well-sm" v-if="noresult">
                @foreach($posts as $post)
                  <p>
                    <strong><a href="#">{{ $post->description }}</a></strong>
                    <span class="alert-danger">On {{ $post->created_at->format('M d,Y \a\t h:i a') }}</span>
                  </p>
                @endforeach
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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 src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.1/vue-resource.min.js"></script>
    <script src="/js/search.js"></script>
  </body>
</html>

search.js

new Vue({
    el: 'body',
    data: {
      posts: [],
      loading: false,
      noresult: 'Showing All Posts',
      query: ''
  },
  methods: {
    search: function() {
        // Clear the error message.
        this.noresult = '';
        // Empty the posts array so we can fill it with the new posts.
        this.posts = [];
        // Set the loading property to true, this will display the "Searching..." button.
        this.loading = true;

        // Making a get request to our API and passing the query to it.
        this.$http.get('/api/search?q=' + this.query).then((response) => {
            // If there was an error set the error message, if not fill the posts array.
            response.body.error ? this.noresult = response.body.error : this.posts = response.body;
            // The request is finished, change the loading to false again.
            this.loading = false;
            // Clear the query.
            this.query = '';
        });
    }
  }
});

More Vue.Js & Laravel Video Tutorial :



Full source code laravel app with vue.js
see you next lessons.

Laravel Scout and Vue.Js : How to create Search Function in Laravel 5.3


Laravel 5.3 tutorial : This lesson will show you how to create simple search function using Laravel Scout and Vue.Js, at the previews lessons we have learn how to build simple search using GET Method, please read Simple Search Function Using GET Method in laravel 5.3.

How to create Search Function in Laravel 5.3?

First, we will need laravel was installed on our server, if not, i assumed you to read and do step by step on this lessons How to build Blog using laravel step by step.

Video tutorial How to create Search Function in Laravel 5.3

Just watch this video, and follow step by step.


Routes (Web and Api)

web.php

Route::get('/','Api\SearchController@search');

api.php

Route::get('/search', 'Api\SearchController@search');

Api Controller (SearchController.php)

<?php
namespace App\Http\Controllers\Api;
use App\Posts;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SearchController extends Controller {
    // we will Installing and configuring Laravel Scout
    public function search(Request $req){
      // First we define the error message we are going to show if no keywords
      $error = ['error'=>'No results found'];
      // if the user entered the keyword
      if ($req->has('q')){
        // Using the Laravel Scout syntax to search the products table.
        $posts = Posts::search($req->get('q'))->get();
        // If there are results return them, if none, return the error message.
        return $posts->count() ? $posts : $error;
      } else {
        // we will show all posts data from database
        $posts = Posts::all();
        return view('search')->withPosts($posts);
      }
    }
}

Search.blade.php

<!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 Vue.Js Search Function</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">
      <div class="row" id="posts">
        <div class="col-md-12">
          <div class="input-group input-group-sm">
            <div class="icon-addon addon-md">
              <input type="text" v-model="query" placeholder="What are you looking for?" class="form-control">
            </div>
            <span class="input-group-btn">
              <button type="button" class="btn-sm btn-danger" v-if="!loading" @click="search()">
                Search <i class="fa fa-search"></i>
              </button>
              <button type="button" class="btn-sm btn-danger" v-if="loading" disabled="disabled">
                Searching... <i class="fa fa-search"></i>
              </button>
            </span>
          </div>
        </div>

        <div class="row">
          <div class="col-md-12">
            <div class="post-preview" v-for="post in posts">
              <p>
                <span class="well-sm"><strong>
                  <a href="#">@{{ post.title }}</a>
                </strong>
                </span>
                <span class="alert-danger">
                  On @{{ post.created_at }}
                </span>
              </p>
            </div>
          </div>
        </div>
      </div>
      <!-- Show all data posts from database -->
      <div class="row">
        <div class="col-md-12">
          <div class="post-preview">
            <div class="alert alert-warning" v-if="noresult">
              <h2><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                @{{ noresult }}
              </h2>
              <span class="well-sm" v-if="noresult">
                @foreach($posts as $post)
                  <p>
                    <strong><a href="#">{{ $post->description }}</a></strong>
                    <span class="alert-danger">On {{ $post->created_at->format('M d,Y \a\t h:i a') }}</span>
                  </p>
                @endforeach
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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 src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.1/vue-resource.min.js"></script>
    <script src="/js/search.js"></script>
  </body>
</html>

search.js

new Vue({
    el: 'body',
    data: {
      posts: [],
      loading: false,
      noresult: 'Showing All Posts',
      query: ''
  },
  methods: {
    search: function() {
        // Clear the error message.
        this.noresult = '';
        // Empty the posts array so we can fill it with the new posts.
        this.posts = [];
        // Set the loading property to true, this will display the "Searching..." button.
        this.loading = true;

        // Making a get request to our API and passing the query to it.
        this.$http.get('/api/search?q=' + this.query).then((response) => {
            // If there was an error set the error message, if not fill the posts array.
            response.body.error ? this.noresult = response.body.error : this.posts = response.body;
            // The request is finished, change the loading to false again.
            this.loading = false;
            // Clear the query.
            this.query = '';
        });
    }
  }
});

More Vue.Js & Laravel Video Tutorial :



Full source code laravel app with vue.js
see you next lessons.

Thứ Tư, 2 tháng 11, 2016

Laravel 5 and Vue.Js : Simple C.R.U.D with Notification and Pagination Example in Laravel 5.3


Laravel Vue.Js Tutorial - How to create simple CRUD (Create, Read, Update, Delete) operations using Laravel 5.3 and vue.js with beauty Notification and pagination in laravel 5.3? at the previews lessons, we have create simple Ajax CRUD in Laravel 5.3, please read Laravel 5 CRUD using AJAX & Modals + Bootstrap Template.

CRUD with Vue.Js in Laravel 5.3

Step 1 - you must create new database "laravelvuejscrud", i'm using MySQL database.
Next, we will create new project using Laravel 5.3

Simple C.R.U.D with Notification and Pagination Example in Laravel 5.3

Create Laravel 5.3 CRUD Project

Install Laravel 5.3 using Composer

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

Create Connection to your Database (MySQL Database)

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelvuejs
DB_USERNAME=root
DB_PASSWORD=yourpassword

Create Table and Migration

php artisan make:migration create_table_blog_tabel

In your new migration file will stored on database\migrations\2016_11_02_210301_create_blog_table.php

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

Next, run Migration

php artisan migrate

Create Model (Blog.php)

php artisan make:model Blog

Your new model will stored on app\Blog.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
  protected $table ='blog_post';
  public $fillable = ['title','description'];
}

Create Controller (BlogController.php)

php artisan make:controller BlogController --resource

Your controller will stored on app\Http\Controllers\BlogController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Blog;
use App\Http\Requests;
use Validator;
use Response;
use Illuminate\Support\Facades\Input;

class BlogController extends Controller
{
    public function vueCrud(){
      return view('/vuejscrud/index');
    }

    public function index()
    {
        $items = Blog::latest()->paginate(6);
        $response = [
          'pagination' => [
            'total' => $items->total(),
            'per_page' => $items->perPage(),
            'current_page' => $items->currentPage(),
            'last_page' => $items->lastPage(),
            'from' => $items->firstItem(),
            'to' => $items->lastItem()
          ],
          'data' => $items
        ];
        return response()->json($response);
    }

    public function store(Request $request)
    {
        $this->validate($request,[
          'title' => 'required',
          'description' => 'required',
        ]);
        $create = Blog::create($request->all());
        return response()->json($create);
    }

    public function update(Request $request, $id)
    {
      $this->validate($request,[
        'title' => 'required',
        'description' => 'required',
      ]);
      $edit = Blog::find($id)->update($request->all());
      return response()->json($edit);
    }
    
    public function destroy($id)
    {
        Blog::find($id)->delete();
        return response()->json(['done']);
    }
}

Create Routes

Route::group(['middleware' => ['web']], function() {
  Route::get('/vuejscrud', 'BlogController@vueCrud');
  Route::resource('vueitems','BlogController');
});

Next, we wil working with views,

Views

Create new file for our Master Blade templates, named with "app.blade.php" that stored on resources\views\app.blade.php

<!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 Laravel Vue.Js CRUD</title>
    <meta id="token" name="token" value="{{ csrf_token() }}">
    <!-- 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" id="manage-vue">
      @yield('content')
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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" 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="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.min.js"></script>
    <script type="text/javascript" src="/js/blog.js"></script>
  </body>
</html>

Create New Page (index.blade.php)

This page will stored on resources\views\vuejscrud\index.blade.php

@extends('app')
@section('content')
  <div class="form-group row add">
    <div class="col-md-12">
      <h1>Simple Laravel Vue.Js Crud</h1>
    </div>
    <div class="col-md-12">
      <button type="button" data-toggle="modal" data-target="#create-item" class="btn btn-primary">
        Create New Post
      </button>
    </div>
  </div>
  <div class="row">
    <div class="table-responsive">
      <table class="table table-borderless">
        <tr>
          <th>Title</th>
          <th>Description</th>
          <th>Actions</th>
        </tr>
        <tr v-for="item in items">
          <td>@{{ item.title }}</td>
          <td>@{{ item.description }}</td>
          <td>
            <button class="edit-modal btn btn-warning" @click.prevent="editItem(item)">
              <span class="glyphicon glyphicon-edit"></span> Edit
            </button>
            <button class="edit-modal btn btn-danger" @click.prevent="deleteItem(item)">
              <span class="glyphicon glyphicon-trash"></span> Delete
            </button>
          </td>
        </tr>
      </table>
    </div>
  </div>
  <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 Item Modal -->
  <div class="modal fade" id="create-item" 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 New Post</h4>
        </div>
        <div class="modal-body">
          <form method="post" enctype="multipart/form-data" v-on:submit.prevent="createItem">
            <div class="form-group">
              <label for="title">Title:</label>
              <input type="text" name="title" class="form-control" v-model="newItem.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="description" class="form-control" v-model="newItem.description">
              </textarea>
              <span v-if="formErrors['description']" class="error text-danger">
                @{{ formErrors['description'] }}
              </span>
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-success">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
<!-- Edit Item Modal -->
<div class="modal fade" id="edit-item" 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 Blog Post</h4>
      </div>
      <div class="modal-body">
        <form method="post" enctype="multipart/form-data" v-on:submit.prevent="updateItem(fillItem.id)">
          <div class="form-group">
            <label for="title">Title:</label>
            <input type="text" name="title" class="form-control" v-model="fillItem.title" />
            <span v-if="formErrorsUpdate['title']" class="error text-danger">
              @{{ formErrorsUpdate['title'] }}
            </span>
          </div>
          <div class="form-group">
            <label for="title">Description:</label>
            <textarea name="description" class="form-control" v-model="fillItem.description">
            </textarea>
            <span v-if="formErrorsUpdate['description']" class="error text-danger">
              @{{ formErrorsUpdate['description'] }}
            </span>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
@stop

Finnally, this step we will working with JavaScript,

blog.js (public\js\blog.js)

Create new file in public\js\blog.js

Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("value");
new Vue({
  el :'#manage-vue',
  data :{
    items: [],
    pagination: {
      total: 0,
      per_page: 2,
      from: 1,
      to: 0,
      current_page: 1
    },
    offset: 4,
    formErrors:{},
    formErrorsUpdate:{},
    newItem : {'title':'','description':''},
    fillItem : {'title':'','description':'','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.getVueItems(this.pagination.current_page);
  },
  methods: {
    getVueItems: function(page) {
      this.$http.get('/vueitems?page='+page).then((response) => {
        this.$set('items', response.data.data.data);
        this.$set('pagination', response.data.pagination);
      });
    },
    createItem: function() {
      var input = this.newItem;
      this.$http.post('/vueitems',input).then((response) => {
        this.changePage(this.pagination.current_page);
        this.newItem = {'title':'','description':''};
        $("#create-item").modal('hide');
        toastr.success('Post Created Successfully.', 'Success Alert', {timeOut: 5000});
      }, (response) => {
        this.formErrors = response.data;
      });
    },
    deleteItem: function(item) {
      this.$http.delete('/vueitems/'+item.id).then((response) => {
        this.changePage(this.pagination.current_page);
        toastr.success('Post Deleted Successfully.', 'Success Alert', {timeOut: 5000});
      });
    },
    editItem: function(item) {
      this.fillItem.title = item.title;
      this.fillItem.id = item.id;
      this.fillItem.description = item.description;
      $("#edit-item").modal('show');
    },
    updateItem: function(id) {
      var input = this.fillItem;
      this.$http.put('/vueitems/'+id,input).then((response) => {
        this.changePage(this.pagination.current_page);
        this.newItem = {'title':'','description':'','id':''};
        $("#edit-item").modal('hide');
        toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});
      }, (response) => {
        this.formErrors = response.data;
      });
    },
    changePage: function(page) {
      this.pagination.current_page = page;
      this.getVueItems(page);
    }
  }
});

Video tutorial C.R.U.D with Notification and Pagination Example using Vue.Js



Laravel 5.3 Simple Ajax CRUD



Subscribe for more tutorials.
Download Full source code C.R.U.D with Notification and Pagination Example in Laravel 5.3 and Vue.js https://goo.gl/wp9xwf

See you next lessons ...

Laravel 5 and Vue.Js : Simple C.R.U.D with Notification and Pagination Example in Laravel 5.3


Laravel Vue.Js Tutorial - How to create simple CRUD (Create, Read, Update, Delete) operations using Laravel 5.3 and vue.js with beauty Notification and pagination in laravel 5.3? at the previews lessons, we have create simple Ajax CRUD in Laravel 5.3, please read Laravel 5 CRUD using AJAX & Modals + Bootstrap Template.

CRUD with Vue.Js in Laravel 5.3

Step 1 - you must create new database "laravelvuejscrud", i'm using MySQL database.
Next, we will create new project using Laravel 5.3

Simple C.R.U.D with Notification and Pagination Example in Laravel 5.3

Create Laravel 5.3 CRUD Project

Install Laravel 5.3 using Composer

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

Create Connection to your Database (MySQL Database)

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelvuejs
DB_USERNAME=root
DB_PASSWORD=yourpassword

Create Table and Migration

php artisan make:migration create_table_blog_tabel

In your new migration file will stored on database\migrations\2016_11_02_210301_create_blog_table.php

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

Next, run Migration

php artisan migrate

Create Model (Blog.php)

php artisan make:model Blog

Your new model will stored on app\Blog.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
  protected $table ='blog_post';
  public $fillable = ['title','description'];
}

Create Controller (BlogController.php)

php artisan make:controller BlogController --resource

Your controller will stored on app\Http\Controllers\BlogController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Blog;
use App\Http\Requests;
use Validator;
use Response;
use Illuminate\Support\Facades\Input;

class BlogController extends Controller
{
    public function vueCrud(){
      return view('/vuejscrud/index');
    }

    public function index()
    {
        $items = Blog::latest()->paginate(6);
        $response = [
          'pagination' => [
            'total' => $items->total(),
            'per_page' => $items->perPage(),
            'current_page' => $items->currentPage(),
            'last_page' => $items->lastPage(),
            'from' => $items->firstItem(),
            'to' => $items->lastItem()
          ],
          'data' => $items
        ];
        return response()->json($response);
    }

    public function store(Request $request)
    {
        $this->validate($request,[
          'title' => 'required',
          'description' => 'required',
        ]);
        $create = Blog::create($request->all());
        return response()->json($create);
    }

    public function update(Request $request, $id)
    {
      $this->validate($request,[
        'title' => 'required',
        'description' => 'required',
      ]);
      $edit = Blog::find($id)->update($request->all());
      return response()->json($edit);
    }
    
    public function destroy($id)
    {
        Blog::find($id)->delete();
        return response()->json(['done']);
    }
}

Create Routes

Route::group(['middleware' => ['web']], function() {
  Route::get('/vuejscrud', 'BlogController@vueCrud');
  Route::resource('vueitems','BlogController');
});

Next, we wil working with views,

Views

Create new file for our Master Blade templates, named with "app.blade.php" that stored on resources\views\app.blade.php

<!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 Laravel Vue.Js CRUD</title>
    <meta id="token" name="token" value="{{ csrf_token() }}">
    <!-- 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" id="manage-vue">
      @yield('content')
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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" 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="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.min.js"></script>
    <script type="text/javascript" src="/js/blog.js"></script>
  </body>
</html>

Create New Page (index.blade.php)

This page will stored on resources\views\vuejscrud\index.blade.php

@extends('app')
@section('content')
  <div class="form-group row add">
    <div class="col-md-12">
      <h1>Simple Laravel Vue.Js Crud</h1>
    </div>
    <div class="col-md-12">
      <button type="button" data-toggle="modal" data-target="#create-item" class="btn btn-primary">
        Create New Post
      </button>
    </div>
  </div>
  <div class="row">
    <div class="table-responsive">
      <table class="table table-borderless">
        <tr>
          <th>Title</th>
          <th>Description</th>
          <th>Actions</th>
        </tr>
        <tr v-for="item in items">
          <td>@{{ item.title }}</td>
          <td>@{{ item.description }}</td>
          <td>
            <button class="edit-modal btn btn-warning" @click.prevent="editItem(item)">
              <span class="glyphicon glyphicon-edit"></span> Edit
            </button>
            <button class="edit-modal btn btn-danger" @click.prevent="deleteItem(item)">
              <span class="glyphicon glyphicon-trash"></span> Delete
            </button>
          </td>
        </tr>
      </table>
    </div>
  </div>
  <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 Item Modal -->
  <div class="modal fade" id="create-item" 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 New Post</h4>
        </div>
        <div class="modal-body">
          <form method="post" enctype="multipart/form-data" v-on:submit.prevent="createItem">
            <div class="form-group">
              <label for="title">Title:</label>
              <input type="text" name="title" class="form-control" v-model="newItem.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="description" class="form-control" v-model="newItem.description">
              </textarea>
              <span v-if="formErrors['description']" class="error text-danger">
                @{{ formErrors['description'] }}
              </span>
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-success">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
<!-- Edit Item Modal -->
<div class="modal fade" id="edit-item" 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 Blog Post</h4>
      </div>
      <div class="modal-body">
        <form method="post" enctype="multipart/form-data" v-on:submit.prevent="updateItem(fillItem.id)">
          <div class="form-group">
            <label for="title">Title:</label>
            <input type="text" name="title" class="form-control" v-model="fillItem.title" />
            <span v-if="formErrorsUpdate['title']" class="error text-danger">
              @{{ formErrorsUpdate['title'] }}
            </span>
          </div>
          <div class="form-group">
            <label for="title">Description:</label>
            <textarea name="description" class="form-control" v-model="fillItem.description">
            </textarea>
            <span v-if="formErrorsUpdate['description']" class="error text-danger">
              @{{ formErrorsUpdate['description'] }}
            </span>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
@stop

Finnally, this step we will working with JavaScript,

blog.js (public\js\blog.js)

Create new file in public\js\blog.js

Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("value");
new Vue({
  el :'#manage-vue',
  data :{
    items: [],
    pagination: {
      total: 0,
      per_page: 2,
      from: 1,
      to: 0,
      current_page: 1
    },
    offset: 4,
    formErrors:{},
    formErrorsUpdate:{},
    newItem : {'title':'','description':''},
    fillItem : {'title':'','description':'','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.getVueItems(this.pagination.current_page);
  },
  methods: {
    getVueItems: function(page) {
      this.$http.get('/vueitems?page='+page).then((response) => {
        this.$set('items', response.data.data.data);
        this.$set('pagination', response.data.pagination);
      });
    },
    createItem: function() {
      var input = this.newItem;
      this.$http.post('/vueitems',input).then((response) => {
        this.changePage(this.pagination.current_page);
        this.newItem = {'title':'','description':''};
        $("#create-item").modal('hide');
        toastr.success('Post Created Successfully.', 'Success Alert', {timeOut: 5000});
      }, (response) => {
        this.formErrors = response.data;
      });
    },
    deleteItem: function(item) {
      this.$http.delete('/vueitems/'+item.id).then((response) => {
        this.changePage(this.pagination.current_page);
        toastr.success('Post Deleted Successfully.', 'Success Alert', {timeOut: 5000});
      });
    },
    editItem: function(item) {
      this.fillItem.title = item.title;
      this.fillItem.id = item.id;
      this.fillItem.description = item.description;
      $("#edit-item").modal('show');
    },
    updateItem: function(id) {
      var input = this.fillItem;
      this.$http.put('/vueitems/'+id,input).then((response) => {
        this.changePage(this.pagination.current_page);
        this.newItem = {'title':'','description':'','id':''};
        $("#edit-item").modal('hide');
        toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});
      }, (response) => {
        this.formErrors = response.data;
      });
    },
    changePage: function(page) {
      this.pagination.current_page = page;
      this.getVueItems(page);
    }
  }
});

Video tutorial C.R.U.D with Notification and Pagination Example using Vue.Js



Laravel 5.3 Simple Ajax CRUD



Subscribe for more tutorials.
Download Full source code C.R.U.D with Notification and Pagination Example in Laravel 5.3 and Vue.js https://goo.gl/wp9xwf

See you next lessons ...