Learn How To Use Vuex In Laravel 7.x Application

In this tutorial we are going to learn how to use vuex in laravel. Do you know why we should use vuex?  We can use props to send data component to component. But using vuex we can do it easily. We can can manage large application easily also. Using vuex your code will be easily readable and understandable. 

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.

You can see documentation of vuex and just see it how its works. Though vuex is littile bit tricky but if you clearly understand it, it will be very helpful for you. Cause we can easily state manage using vuex in vue application. 

In this tutorial i will create a Category table and read or fetch all the categories data using vuex from database. Now i am going to show you how we can do it using vuex in our vue and laravel application.

In this laravel vuex tutorial we will see from scratch how to retrive data from database using vuex. Let's see laravel vuex tutorial and learn how to add it to our existing project or new project.

how-to-use-vuex-in-laravel

 

Step 1: Laravel Installation

In first step, If you haven't installed Laravel in your system then you have to run bellow command and get fresh Laravel project.

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

 

Step 2: Create table and model

Run below command to create model and its corresponding table

php artisan make:model Category -m

 

In this step i will use Category model and uploads table to create vuex laravel application. So paste this below code to your categories table.

Schema::create('uploads', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('slug');
    $table->boolean('status)
    $table->timestamps();
});

 

Now run migration command after setup your database. 

 

Step 3: Define the API routes

Now, we need to define the API routes inside the routes >> api.php file.

routes/api.php

Route::apiResources(
	[
		'category' => 'API\CategoryController'
	]
);

 

Step 4: Create Controller

To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

php artisan make:controller API/CategoryController --api

 

Ok, now we have created new controller as UserController in this path app/Http/Controllers/API/CategoryController.php. this controller will manage all route method:

 

Step 5 : Install Vue dependency and edit configurations

Now, go inside the project folder and install the frontend dependencies using the following command.

 

Read also : User Roles and Permissions Tutorial in Laravel without Packages

 

npm install

 

Run below command to install vuex via npm

npm install vuex --save

 

Step 6: Setup app.js file

resources/js/app.js

require('./bootstrap');

window.Vue = require('vue');

//support vuex
import Vuex from 'vuex'
Vue.use(Vuex)
import storeData from "./store/index"

const store = new Vuex.Store(
   storeData
)

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

const app = new Vue({

    el: '#app',

    store, //vuex

});

 

Read also Laravel Vue Js CRUD example using Vue Router

 

resources/js/store/index.js

export default {

	state: {

       category: []

	},

	getters: {

       getCategoryFormGetters(state){ //take parameter state

          return state.category
       }
	},

	actions: {
       allCategoryFromDatabase(context){

          axios.get("api/category")

               .then((response)=>{
                  console.log(response.data.categories)
                  context.commit("categories",response.data.categories) //categories will be run from mutation

               })

               .catch(()=>{
                  
                  console.log("Error........")
                  
               })
       }
	},

	mutations: {
       categories(state,data) {
          return state.category = data
       }
	}
}

 

Look what is happening here? 

state: In state we've defined a empty category array so that when we will return category then we will just put all the category inside category array. 

getters In getters we will define our method which takes one parameter state. Using state we can access value of state. So here i just create a method like getCategoryFormGetters(state) and given a parameter state and then access category array using state and just retun it.

actions In action i define a method like allCategoryFromDatabase which comes form dispatch method. Just see below exampleComponent mountend() method. Hope you will get it. So if i give a function name abc inside dispatch() then in action we have to declare it as same name. 

in this statement context.commit("categories",response.data.categories) here i commit a function categories and give our incoming data from controller. Inside mutations just we have to declare it. 

mutations: Here i just declare categories function which comes commit that mean this statement context.commit("categories",response.data.categories). Here i just assign all the data category array. Hope you will understand.

 

resources/js/component/ExampleComponent.vue

 

Look here using our store constant we can access state,actions, getters or mutations data like that.

App\Http\Controllers\API\CategoryController.php

namespace App\Http\Controllers\API;

use App\Category;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class CategoryController extends Controller
{

    public function index()
    {
        $categories = Category::latest()->get();

        return response()->json([
           "categories" => $categories
        ],200);
    }

}

 

resources/views/home.blade.php

 

Now go to your web.php and write this following code.

Route::view('/home', 'home');

 

Read also : Vue Laravel CRUD Example With Vue Router & Sweet Alert

 

Now run this following command to compile all js files.

npm run dev

 

Hope it will help you. If you face any error then you can share with me. 

 

#laravel #laravel-6 #vue-js #vuex #axios