X
    Categories: LaravelVue.js

Filter posts based on category using Laravel 5.5 and Vue js

Filter posts based on category using Laravel 5.5 and Vue js

Hello Everyone, This is a simple application which going to explain the concept of how to filter the posts based in category click using laravel 5.5 and vue js. Laravel 5.5 by default come with Vue js. There are 3 presets available in laravel 5.5 1. bootstrap, Vue and React. Here we are going to see with Vue js.

Step 1

Create 2 tables
1. Categories
2. Posts

php artisan make:migration create_category_table
php artisan make:migration create_posts_table

2017_09_26_062649_create_category_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

2017_09_26_063729_create_posts_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('category_id')->unsigned();
            $table->string('name')->nullabe();
            $table->mediumText('description')->nullabe();
            $table->timestamps();

            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Step 2 : Run migration to create tables to database

php artisan migrate

Step 3

Create dummy categories to categories table

Step 4

Create dummy posts with reference of category id

Step 5

Make Category.php and Post.php Models

Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name'
    ];
}

Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'category_id',
        'name',
        'description'
    ];
}

Step 6

Write route and controller to return data

routes/web.php

Route::get('/customers/list/filter', 'HomeController@filter');

Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use App\Post;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
     /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function filter()
    {
        $data['categories'] = Category::all();
        $data['posts'] = Post::all();
        return response($data, 200)
                  ->header('Content-Type', 'text/plain');
    }
}

Step 7

Write a code to fetch post and categories at your app.js

app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app',
    data : {
    	categories : [],
    	posts : [],
    	allPosts : [],
    },
    created: function () {
	    // `this` points to the vm instance
	    this.fetchPosts();
     },
     methods: {
     	fetchPosts: function() {
     		console.log("Function Triggered");
     		axios.get('http://localhost:8080/laravel55/public/customers/list/data')
		    .then(response => {
		        console.log(response.data);
		        this.categories = response.data.categories;
		        this.posts = response.data.posts;
		        this.allPosts = this.posts;
		    }).catch(error => {
			    console.log(error)
			});
     	}
     }
});

Step 8

Write a blade to display contents in front end

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif
                    <div class="row">
                          <div class="col-sm-2">
                            <div class="row" style="margin-bottom: 15px; cursor: pointer;color: cornflowerblue;">
                                <div class="col-sm-12" @click="filterByCategory('all')">
                                    All
                                </div>
                              </div>
                              <div class="row" style="margin-bottom: 15px; cursor: pointer; color: cornflowerblue;" v->
Step 9
In above blade you can see "filterByCategory()" function which going to help us to filter the posts Write a filter function inside "methods" at your app.js
filterByCategory : function(id) {
     		this.posts = _.filter(this.allPosts, function(post) {
     			return post.category_id === id || id == 'all' ;
     		});
     		if (id && id !== window.location.href.split('?')[1]) {
     			console.log(id)
		        window.history.replaceState({}, "", '?' + id);
		        document.title = "Title: " + id;
		    }
     	}

Step 10

run npm run dev (or)
npm run watch 
command to compile assets.

now run your app and based on user click you can filter the data

Thats it. It will help someone else.

Output

 

Marimuthu: