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.
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.
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.
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)
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.
In the above snippet, for button, I used@click.prevent="createItem()"
which callscreateItem
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 likecreateItem()
var app = new Vue({ el: '#vue-crud-wrapper', data: { ... items: [], hasError: true, 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(); }); } }
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!
Here the classhidden
is bonded with the variablehasError
, so ifhasError
istrue
that class is applied. That is why I sethasError
tofalse
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 theweb.php
file at/routes
directory
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; }
Here I used a modelData
which has all the details related to database table the data is being stored. So in theapp
directory, I create a new model namedData.php
with the following class.
class Data extends Model { protected $table = "vueCrudData"; public $timestamps = false; }
Now when$data->save();
is executed, all the data will be stored in thevueCrudData
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.
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(); },
getVueItems method,
getVueItems: function getVueItems() { var _this = this; axios.get('/vueitems').then(function (response) { _this.items = response.data; }); }
Now the data is set in the variableitems
, 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' );
readItems function in MainController,
public function readItems() { $data = Data::all (); return $data; }
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.
So when clicked it calls deleteItem(item)
method.
deleteItem: function deleteItem(item) { var _this = this; axios.post('/vueitems/' + item.id).then(function (response) { _this.getVueItems(); _this.hasDeleted = false }); }
this method simply calls /vueitems/id
route which calls Laravel deleteItem function. the route,
Route::post ( '/vueitems/{id}', 'MainController@deleteItem' );
deleteItem
function in MainController,
public function deleteItem(Request $request) { $data = Data::find ( $request->id )->delete (); }
The item gets deleted, and in the vue response function getVueItems
is called, do the items are updated.
Vue js CRUD App – justlaravel.com
So finally all the CRUD(Create, Read, Update, Delete) operations are performed using vue js and laravel. You can also find all Vue related tutorials at https://justlaravel.com/category/vue-js/
ID | Name | Age | Profession | Actions |
---|---|---|---|---|
{ this.getVueItems(); this.showModal=false }); }
The first four lines gets all the info from the modal using Route::post ( '/edititems/{id}', 'MainController@editItem' ); The editItem function in MainController, public function editItem(Request $request, $id){ $data =Data::where('id', $id)->first(); $data->name = $request->get('val_1'); $data->age = $request->get('val_2'); $data->profession = $request->get('val_3'); $data->save(); return $data; } The above snippet will fetch the row with the given id, and update its elements name, age, and profession. Delete OperationIn the actions column there is an icon for delete, |