At Last, finally we are in last stage of our laravel vuejs crud tutorial. In last post we have written about how to update records into database using vuejs and laravel.
If you are new to this article please visit our last written post at Laravel VueJS 2 Crud Application Part 3 or may be you can start from Setting Up Laravel and VueJS 2 Project. This will help you better understand on what this article is about.
Without waiting much time lets finish our final part of our laravel vuejs 2 crud tutorial series.
Lets get started
Till now our directory structure looks like this.
To delete the records from the database we just need to follow these simple steps below.
- Add
@click
event which trigger a function and pass category id to it. - Create new
deleteCategory()
function insideViewCategory
component methods section. - Create routes in
api.php
and delete function insideCategoryController.php
in laravel. - Write a javascript code to remove the record which was pressed delete.
Lets add click event to the buttons. Open up ViewCategory.vue
and changes this line.
1 |
<a class="btn btn-danger btn-xs">Delete Category</a> |
to this
1 |
<a @click="deleteCategory(category.id)" class="btn btn-danger btn-xs">Delete Category</a> |
Add new function named deleteCategory()
just after viewCategories()
function.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
deleteCategory(id) { let instance = this; axios.get('api/categories/'+id+'/delete') .then(function (response) { $('#div'+id).fadeOut(300, function() { console.log("deleted"); }) }) .catch(function (error) { console.log(error); }); } |
Also,
Change this line :
1 |
<tr v-for="(category,index) in categories_list"> |
to this :
1 |
<tr v-for="(category,index) in categories_list" :id="'div'+category.id"> |
Now we have finished our task in VueJS. Time to configure routes and controller in laravel.
Go to routes/api.php
and add this line.
1 |
Route::get("categories/{id}/delete",'CategoryController@deleteCategory'); |
Go to CategoryController.php
inside app/Http/Controllers
and add this function.
1 2 3 4 5 |
public function deleteCategory($id) { $data = tbl_category::find($id); $data->delete(); return Response::json(true); } |
Finally hit php artisan serve
and npm run watch
in order to test the application.
Good going, you have finally completed laravel vuejs crud tutorial series. If you want to take a look at the sample application we build during our series, you can download them by clicking this link.
If you have any problem, you can mention via comments or contact us via contact page.
Leave a Reply