Vue Js and Laravel – CRUD Operations

Hello artisans, welcome to justlaravel.com. Here am going to show you how to perform CRUD operations with Vue.js and Laravel. I have previously discussed Vue js in my previous tutorials where I created a simple search app, and some introduction to Vue, so here I am going to make a complete CRUD app using Vue.js and Laravel.

Let’s get started!

Setting up Vue js

We first need to setup Vue in our project. Its a breeze in Laravel as it is already included with Vue, we just need to install some modules to get started with Vue.

  • Create a laravel project: laravel new VueCRUD
  • Install PHP packages: go to VueCRUD directory and run composer install
  • Generate a key: php artisan key:generate
  • Install node packages: npm install
  • Run the app: npm run watch to make the changes to take effect immediately and also run php artisan serve for the checking the actual app.

Overview of the app

The app will display a list of people with the name, age and their profession, with edit and delete options, and 3 fields to add a new item.

Vue.js CRUD App – justlaravel.com

You can also watch the video on YouTube here.

Initialize Vue js

All the Vue(js) part is written in fileapp.js in /resources/assets/js directory.

First I will create a new vue instance, and all the vue part is handled in an element with id vue-crud-wrapper i.e all the HTML content is wrapped in a div with id vue-crud-wrapper.

…. … … … ….

Create a new vue instance(app.js)

const app = new Vue({ el: “#vue-crud-wrapper”, data: { …. }, methods: { …. }, …. });

Add Person Form(Create Operation)

Here a form is shown with 3 fields name, age, and profession with a button which when clicked calls the action in the js and performs the add operation.

Name: Age: Profession: ADD

    Name:          Age:          Profession:      ADD

In the above snippet, for button, I used @click.prevent="createItem()" which calls createItem vue method which is declared in the file/resources/assets/js/app.js.

So in the vue, I initialize some variables, which can be used in the methods like createItem()

var app = new Vue({ el: ‘#vue-crud-wrapper’, data: { … items: [], hasError: true, newItem: { ‘name’: ”,’age’: ”,’profession’: ” }, }, … …

    newItem: { ‘name’: ”,’age’: ”,’profession’: ” },

Here I also check for empty fields and throw an error when the input field is empty, so I initialize that hasError variable.

createItem: function createItem() { var _this = this; var input = this.newItem; if (input[‘name’] == ” || input[‘age’] == ” || input[‘profession’] == ” ) { this.hasError = false; } else { this.hasError = true; axios.post(‘/vueitems’, input).then(function (response) { _this.newItem = { ‘name’: ” }; _this.getVueItems(); }); } }

createItem: function createItem() {       var input = this.newItem;       if (input[‘name’] == ” || input[‘age’] == ” || input[‘profession’] == ” ) {         axios.post(‘/vueitems’, input).then(function (response) {           _this.newItem = { ‘name’: ” };

So when the fields are empty, I change the hasError variable to false, and a condition is written in the view to display error when the variable is set to false.

Please fill all fields!

Please fill all fields!

Here the class hidden is bonded with the variable hasError,  so if hasError is true that class is applied.

That is why I set hasError to false when there is an error.

Next, if all the fields are filled, I make a post call using axios and pass the data entered in the form. All the data that to be stored in the input variable and it is passed as an argument to the post function.

axios.post('/vueitems', input)

So this route /vueitems will call to a controller where the data is stored in the database.

In the web.php file at /routes directory

Route::post ( ‘/vueitems’, ‘MainController@storeItem’ );

Route::post ( ‘/vueitems’, ‘MainController@storeItem’ );

We can create a new controller by running the command php artisan:make controller MainController

Now in the MainController(/app/Http/Controllers),

public function storeItem(Request $request) { $data = new Data (); $data->name = $request->name; $data->age = $request->age; $data->profession = $request->profession; $data->save (); return $data; }

public function storeItem(Request $request) {     $data->name = $request->name;     $data->age = $request->age;     $data->profession = $request->profession;

Here I used a model Data which has all the details related to database table the data is being stored.

So in the app directory, I create a new model named Data.php with the following class.

class Data extends Model { protected $table = “vueCrudData”; public $timestamps = false; }

class Data extends Model {     protected $table = “vueCrudData”;     public $timestamps = false;

Now when $data->save(); is executed, all the data will be stored in the vueCrudData table in the database.

Read Operation

Here the data is displayed in the table as shown in the image above. I use some vue properties and binding to the table elements so the data can be displayed as I wanted.

ID Name Age Profession Actions
@{{ item.id }} @{{ item.name }} @{{ item.age }} @{{ item.profession }}
@{{ item.name }} @{{ item.profession }}

In the above snippet, I used v-for directive to repeat all the items, also used some click methods which are used to update and delete items, which I will discuss in next section.

So the data in items variable is stored through js, let’s see it.

There is a hook in vue called mounted. this hook calls immediately when a page loads or vue instance loads. So here in this hook, I call a method called getVueItems(), in this method a call to Laravel Controller and there it fetches the data and returns the same to view.

mounted: function mounted() { this.getVueItems(); },

mounted: function mounted() {

getVueItems method,

getVueItems: function getVueItems() { var _this = this; axios.get(‘/vueitems’).then(function (response) { _this.items = response.data; }); }

getVueItems: function getVueItems() {   axios.get(‘/vueitems’).then(function (response) {     _this.items = response.data;

Now the data is set in the variable items, so iterating(v-for) this variable shows us all the data we need for the view.

So the route /vueitems routes to,

Route::get ( ‘/vueitems’, ‘MainController@readItems’ );

Route::get ( ‘/vueitems’, ‘MainController@readItems’ );

readItems function in MainController,

public function readItems() { $data = Data::all (); return $data; }

public function readItems() {

The above snippet is very simple and straightforward, it gets all the data from the database and returns it and that data is shown in the view using Vue js.

Update Operation

The table containing all the data is presented with two buttons “Edit” and “Delete” under “Actions” column.

So when edit button is clicked, a modal is shown with that particular row’s data and an option to edit them.

You might also like