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ứ Tư, 22 tháng 11, 2017

Laravel 5.5 CRUD Tutorial With Example From Scratch Resource Controller


Laravel 5.5 tutorial for beginners : this tutorial will show you how to create simple laravel apps CRUD (create, read, update, delete) with resource controller in laravel 5.5.


Video tutorial  How to create CRUD Operations in Laravel 5.5



Full source Code Laravel 5.5 Crud Applications

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

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppPost;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        $posts = Post::latest()->paginate(5);
        return view('posts.index', compact('posts'))->with('i',(request()->input('page',1) -1) *5);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        request()->validate([
          'title' => 'required',
          'body' => 'required',
        ]);
        Post::create($request->all());
        return redirect()->route('posts.index')->with('success','Post created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function show($id)
    {
        $post = Post::find($id);
        return view('posts.show', compact('post'));
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, $id)
    {
      request()->validate([
        'title' => 'required',
        'body' => 'required',
      ]);
      Post::find($id)->update($request->all());
      return redirect()->route('posts.index')->with('success','Post updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        Post::find($id)->delete();
        return redirect()->route('posts.index')->with('success','Post deleted successfully');
    }
}

Route

Route::resource('posts','PostController');

Install Laravel Collective (Html and Form)

composer require laravelcollective/html

Modife your config/app.php files

'providers' => [
 ....
 CollectiveHtmlHtmlServiceProvider::class,
],
'aliases' [
 ....
 'Form' => CollectiveHtmlFormFacade::class,
    'Html' => CollectiveHtmlHtmlFacade::class,
],


Next, create new view (Master, Index, Edit, Show, Create, Form)

Master.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 Crud with Resource Controller</title>

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

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>

    <div class="container">
      @yield('content')
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/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>

Index.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <h3>Simple laravel CRUD with resource controller</h3>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-12">
      <div class="pull-right">
        <a class="btn btn-xs btn-success" href="{{ route('posts.create') }}">Create New Post</a>
      </div>
    </div>
  </div>
  @if ($message = Session::get('success'))
    <div class="alert alert-success">
      <p>{{ $message }}</p>
    </div>
  @endif

  <table class="table table-bordered">
    <tr>
      <th>No.</th>
      <th>Title</th>
      <th>Body</th>
      <th width="300px">Actions</th>
    </tr>

    @foreach ($posts as $post)
      <tr>
        <td>{{ ++$i }}</td>
        <td>{{ $post->title }}</td>
        <td>{{ $post->body }}</td>
        <td>
          <a class="btn btn-xs btn-info" href="{{ route('posts.show', $post->id) }}">Show</a>
          <a class="btn btn-xs btn-primary" href="{{ route('posts.edit', $post->id) }}">Edit</a>

          {!! Form::open(['method' => 'DELETE', 'route'=>['posts.destroy', $post->id], 'style'=> 'display:inline']) !!}
          {!! Form::submit('Delete',['class'=> 'btn btn-xs btn-danger']) !!}
          {!! Form::close() !!}
        </td>
      </tr>
    @endforeach
  </table>
  {!! $posts->links() !!}
@endsection

Form.blade.php

<div class="row">
  <div class="col-xs-12">
    <div class="form-group">
      <strong>Title : </strong>
      {!! Form::text('title', null, ['placeholder'=>'Title','class'=>'form-control']) !!}
    </div>
  </div>
  <div class="col-xs-12">
    <div class="form-group">
      <strong>Body : </strong>
      {!! Form::textarea('body', null, ['placeholder'=>'Body','class'=>'form-control','style'=>'height:150px']) !!}
    </div>
  </div>
  <div class="col-xs-12">
    <a class="btn btn-xs btn-success" href="{{ route('posts.index') }}">Back</a>
    <button type="submit" class="btn btn-xs btn-primary" name="button">Submit</button>
  </div>
</div>

Create.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <div class="pull-left">
        <h3>Add New Post</h3>
      </div>
    </div>
  </div>

  @if(count($errors) > 0)
    <div class="alert alert-danger">
      <strong>Whooops!! </strong> There were some problems with your input.<br>
      <ul>
        @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
        @endforeach
      </ul>
    </div>
  @endif

  {!! Form::open(['route' => 'posts.store', 'method' => 'POST']) !!}
    @include('posts.form')
  {!! Form::close() !!}

@endsection

Show.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <div class="pull-left">
        <h3>Show Post </h3> <a class="btn btn-xs btn-primary" href="{{ route('posts.index') }}">Back</a>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-xs-12">
      <div class="form-group">
        <strong>Title : </strong>
        {{ $post->title }}
      </div>
    </div>
    <div class="col-xs-12">
      <div class="form-group">
        <strong>Body : </strong>
        {{ $post->body }}
      </div>
    </div>
  </div>
  
@endsection

Edit.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <div class="pull-left">
        <h3>Edit Post</h3>
      </div>
    </div>
  </div>

  @if(count($errors) > 0)
    <div class="alert alert-danger">
      <strong>Whooops!! </strong> There were some problems with your input.<br>
      <ul>
        @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
        @endforeach
      </ul>
    </div>
  @endif

  {!! Form::model($post, ['method'=>'PATCH','route'=>['posts.update', $post->id]])!!}
    @include('posts.form')
  {!! Form::close() !!}

@endsection


More Laravel Video Tutorial






Laravel 5.5 CRUD Tutorial With Example From Scratch Resource Controller


Laravel 5.5 tutorial for beginners : this tutorial will show you how to create simple laravel apps CRUD (create, read, update, delete) with resource controller in laravel 5.5.


Video tutorial  How to create CRUD Operations in Laravel 5.5



Full source Code Laravel 5.5 Crud Applications

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

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppPost;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        $posts = Post::latest()->paginate(5);
        return view('posts.index', compact('posts'))->with('i',(request()->input('page',1) -1) *5);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        request()->validate([
          'title' => 'required',
          'body' => 'required',
        ]);
        Post::create($request->all());
        return redirect()->route('posts.index')->with('success','Post created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function show($id)
    {
        $post = Post::find($id);
        return view('posts.show', compact('post'));
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, $id)
    {
      request()->validate([
        'title' => 'required',
        'body' => 'required',
      ]);
      Post::find($id)->update($request->all());
      return redirect()->route('posts.index')->with('success','Post updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        Post::find($id)->delete();
        return redirect()->route('posts.index')->with('success','Post deleted successfully');
    }
}

Route

Route::resource('posts','PostController');

Install Laravel Collective (Html and Form)

composer require laravelcollective/html

Modife your config/app.php files

'providers' => [
 ....
 CollectiveHtmlHtmlServiceProvider::class,
],
'aliases' [
 ....
 'Form' => CollectiveHtmlFormFacade::class,
    'Html' => CollectiveHtmlHtmlFacade::class,
],


Next, create new view (Master, Index, Edit, Show, Create, Form)

Master.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 Crud with Resource Controller</title>

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

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>

    <div class="container">
      @yield('content')
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/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>

Index.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <h3>Simple laravel CRUD with resource controller</h3>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-12">
      <div class="pull-right">
        <a class="btn btn-xs btn-success" href="{{ route('posts.create') }}">Create New Post</a>
      </div>
    </div>
  </div>
  @if ($message = Session::get('success'))
    <div class="alert alert-success">
      <p>{{ $message }}</p>
    </div>
  @endif

  <table class="table table-bordered">
    <tr>
      <th>No.</th>
      <th>Title</th>
      <th>Body</th>
      <th width="300px">Actions</th>
    </tr>

    @foreach ($posts as $post)
      <tr>
        <td>{{ ++$i }}</td>
        <td>{{ $post->title }}</td>
        <td>{{ $post->body }}</td>
        <td>
          <a class="btn btn-xs btn-info" href="{{ route('posts.show', $post->id) }}">Show</a>
          <a class="btn btn-xs btn-primary" href="{{ route('posts.edit', $post->id) }}">Edit</a>

          {!! Form::open(['method' => 'DELETE', 'route'=>['posts.destroy', $post->id], 'style'=> 'display:inline']) !!}
          {!! Form::submit('Delete',['class'=> 'btn btn-xs btn-danger']) !!}
          {!! Form::close() !!}
        </td>
      </tr>
    @endforeach
  </table>
  {!! $posts->links() !!}
@endsection

Form.blade.php

<div class="row">
  <div class="col-xs-12">
    <div class="form-group">
      <strong>Title : </strong>
      {!! Form::text('title', null, ['placeholder'=>'Title','class'=>'form-control']) !!}
    </div>
  </div>
  <div class="col-xs-12">
    <div class="form-group">
      <strong>Body : </strong>
      {!! Form::textarea('body', null, ['placeholder'=>'Body','class'=>'form-control','style'=>'height:150px']) !!}
    </div>
  </div>
  <div class="col-xs-12">
    <a class="btn btn-xs btn-success" href="{{ route('posts.index') }}">Back</a>
    <button type="submit" class="btn btn-xs btn-primary" name="button">Submit</button>
  </div>
</div>

Create.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <div class="pull-left">
        <h3>Add New Post</h3>
      </div>
    </div>
  </div>

  @if(count($errors) > 0)
    <div class="alert alert-danger">
      <strong>Whooops!! </strong> There were some problems with your input.<br>
      <ul>
        @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
        @endforeach
      </ul>
    </div>
  @endif

  {!! Form::open(['route' => 'posts.store', 'method' => 'POST']) !!}
    @include('posts.form')
  {!! Form::close() !!}

@endsection

Show.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <div class="pull-left">
        <h3>Show Post </h3> <a class="btn btn-xs btn-primary" href="{{ route('posts.index') }}">Back</a>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-xs-12">
      <div class="form-group">
        <strong>Title : </strong>
        {{ $post->title }}
      </div>
    </div>
    <div class="col-xs-12">
      <div class="form-group">
        <strong>Body : </strong>
        {{ $post->body }}
      </div>
    </div>
  </div>
  
@endsection

Edit.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <div class="pull-left">
        <h3>Edit Post</h3>
      </div>
    </div>
  </div>

  @if(count($errors) > 0)
    <div class="alert alert-danger">
      <strong>Whooops!! </strong> There were some problems with your input.<br>
      <ul>
        @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
        @endforeach
      </ul>
    </div>
  @endif

  {!! Form::model($post, ['method'=>'PATCH','route'=>['posts.update', $post->id]])!!}
    @include('posts.form')
  {!! Form::close() !!}

@endsection


More Laravel Video Tutorial






Laravel 5.5 CRUD Tutorial With Example From Scratch Resource Controller


Laravel 5.5 tutorial for beginners : this tutorial will show you how to create simple laravel apps CRUD (create, read, update, delete) with resource controller in laravel 5.5.


Video tutorial  How to create CRUD Operations in Laravel 5.5



Full source Code Laravel 5.5 Crud Applications

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

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppPost;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        $posts = Post::latest()->paginate(5);
        return view('posts.index', compact('posts'))->with('i',(request()->input('page',1) -1) *5);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        request()->validate([
          'title' => 'required',
          'body' => 'required',
        ]);
        Post::create($request->all());
        return redirect()->route('posts.index')->with('success','Post created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function show($id)
    {
        $post = Post::find($id);
        return view('posts.show', compact('post'));
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, $id)
    {
      request()->validate([
        'title' => 'required',
        'body' => 'required',
      ]);
      Post::find($id)->update($request->all());
      return redirect()->route('posts.index')->with('success','Post updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        Post::find($id)->delete();
        return redirect()->route('posts.index')->with('success','Post deleted successfully');
    }
}

Route

Route::resource('posts','PostController');

Install Laravel Collective (Html and Form)

composer require laravelcollective/html

Modife your config/app.php files

'providers' => [
 ....
 CollectiveHtmlHtmlServiceProvider::class,
],
'aliases' [
 ....
 'Form' => CollectiveHtmlFormFacade::class,
    'Html' => CollectiveHtmlHtmlFacade::class,
],


Next, create new view (Master, Index, Edit, Show, Create, Form)

Master.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 Crud with Resource Controller</title>

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

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>

    <div class="container">
      @yield('content')
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/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>

Index.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <h3>Simple laravel CRUD with resource controller</h3>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-12">
      <div class="pull-right">
        <a class="btn btn-xs btn-success" href="{{ route('posts.create') }}">Create New Post</a>
      </div>
    </div>
  </div>
  @if ($message = Session::get('success'))
    <div class="alert alert-success">
      <p>{{ $message }}</p>
    </div>
  @endif

  <table class="table table-bordered">
    <tr>
      <th>No.</th>
      <th>Title</th>
      <th>Body</th>
      <th width="300px">Actions</th>
    </tr>

    @foreach ($posts as $post)
      <tr>
        <td>{{ ++$i }}</td>
        <td>{{ $post->title }}</td>
        <td>{{ $post->body }}</td>
        <td>
          <a class="btn btn-xs btn-info" href="{{ route('posts.show', $post->id) }}">Show</a>
          <a class="btn btn-xs btn-primary" href="{{ route('posts.edit', $post->id) }}">Edit</a>

          {!! Form::open(['method' => 'DELETE', 'route'=>['posts.destroy', $post->id], 'style'=> 'display:inline']) !!}
          {!! Form::submit('Delete',['class'=> 'btn btn-xs btn-danger']) !!}
          {!! Form::close() !!}
        </td>
      </tr>
    @endforeach
  </table>
  {!! $posts->links() !!}
@endsection

Form.blade.php

<div class="row">
  <div class="col-xs-12">
    <div class="form-group">
      <strong>Title : </strong>
      {!! Form::text('title', null, ['placeholder'=>'Title','class'=>'form-control']) !!}
    </div>
  </div>
  <div class="col-xs-12">
    <div class="form-group">
      <strong>Body : </strong>
      {!! Form::textarea('body', null, ['placeholder'=>'Body','class'=>'form-control','style'=>'height:150px']) !!}
    </div>
  </div>
  <div class="col-xs-12">
    <a class="btn btn-xs btn-success" href="{{ route('posts.index') }}">Back</a>
    <button type="submit" class="btn btn-xs btn-primary" name="button">Submit</button>
  </div>
</div>

Create.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <div class="pull-left">
        <h3>Add New Post</h3>
      </div>
    </div>
  </div>

  @if(count($errors) > 0)
    <div class="alert alert-danger">
      <strong>Whooops!! </strong> There were some problems with your input.<br>
      <ul>
        @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
        @endforeach
      </ul>
    </div>
  @endif

  {!! Form::open(['route' => 'posts.store', 'method' => 'POST']) !!}
    @include('posts.form')
  {!! Form::close() !!}

@endsection

Show.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <div class="pull-left">
        <h3>Show Post </h3> <a class="btn btn-xs btn-primary" href="{{ route('posts.index') }}">Back</a>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-xs-12">
      <div class="form-group">
        <strong>Title : </strong>
        {{ $post->title }}
      </div>
    </div>
    <div class="col-xs-12">
      <div class="form-group">
        <strong>Body : </strong>
        {{ $post->body }}
      </div>
    </div>
  </div>
  
@endsection

Edit.blade.php

@extends('posts.master')

@section('content')
  <div class="row">
    <div class="col-lg-12">
      <div class="pull-left">
        <h3>Edit Post</h3>
      </div>
    </div>
  </div>

  @if(count($errors) > 0)
    <div class="alert alert-danger">
      <strong>Whooops!! </strong> There were some problems with your input.<br>
      <ul>
        @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
        @endforeach
      </ul>
    </div>
  @endif

  {!! Form::model($post, ['method'=>'PATCH','route'=>['posts.update', $post->id]])!!}
    @include('posts.form')
  {!! Form::close() !!}

@endsection


More Laravel Video Tutorial






Laravel 5.5 Socialite Login With Social Media Facebook, Twitter #Part2


Laravel 5.5 tutorial for beginners : this lesson will show you how to create login or register with facebook in laravel 5.5 apps using socialite package.

at the previews lesson, we have create simple login with twitter using socialite, just open this link Laravel 5.5 login with Twitter

Video Tutorial Socialite Login with Facebook


Video Tutorial Laravel 5.5 Socialite Login with Twitter 



Setting up Facebook App

First step you need to create new Facebook app, just follow this link developers.facebook.com

Then, create your first facebook login app.

Adding Services Laravel Project

Next, add facebook services to our services in config/services.php file

'facebook' => [
      'client_id' => '289510921554599',
      'client_secret' => 'd099adaa59b928962e98584555645883',
      'redirect' => 'http://scqq.dev/login/facebook/callback'
    ],


See you next lessons ...