Welcome to part 3 of the laravel vuejs crud tutorial. In this tutorial we are going to update data into database using vuejs 2 and laravel.
If you haven’t been to any of our tutorial make sure you visit last post that we wrote earlier, it will make clear understanding on what we are doing here. You can visit link below to go to last post.
Laravel VueJS 2 CRUD Example Part 2 (Insert into Database)
To Update the data into database first we need to pull the data from database and then edit it and then again update the fresh updated copy into the database.
I have used laravel migration in order to create model named tbl_category
and like wise migration. You can check the copy of migration below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTblCategoriesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tbl_categories', function (Blueprint $table) { $table->increments('id'); $table->string('category_title'); $table->string("category_description"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tbl_categories'); } } |
I have generated some fake data to use as dummy in this project. If you know how to use faker then go ahead and generate some dummy data. Here i have list of my dummy data from MySQL database.
Here you can see the list of data i have prepared in order to edit and update the data into database.
Looks like now we have everything ready in our side with all the necessary data.
Lets get started
Like in any other application, we first need to :
- Get all the records from database.
- Click the record we want to edit.
- Populate it in the form.
- Click save and update into database.
We are going to follow same above steps step by step so that you can get clear understanding on how we are working here with VueJS.
We already have fetched all the records from database in our ViewCategory
component and we only have to edit some part inside it in order to make it work.
We always know that we pass id
of our record to fetch the data from database. Here similar we will pass the id
of an record we want to edit and populate into new component called UpdateCatgory.vue
.
Lets create one,
Create new component called UpdateCategory.vue
and register the component inside routes.js
. Since, we are sending an id
of an data we need to enable props. Now your routes.js
should look like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import VueRouter from 'vue-router'; import Home from './components/Home'; import ViewCategory from './components/category/ViewCategory'; import AddCategory from './components/category/addCategory'; import UpdateCategory from './components/category/UpdateCategory'; let routes = [ { path:"/", component:Home }, { path:"/categories", component:ViewCategory }, { path:"/categories/add", component:AddCategory }, { path:"/categories/:id/edit", name:"UpdateCategory", component:UpdateCategory, props:true } ]; export default new VueRouter({ //mode:'history', routes }); |
Go to ViewCategory.vue
component and edit this line
1 |
<a class="btn btn-default btn-xs">Edit Category</a> |
to this line:
1 |
<router-link :to="{name: 'UpdateCategory', params: {id: category.id}}" class="btn btn-default btn-xs">Edit Category</router-link> |
Now, if you click on it you will be redirected to UpdateCategory
component and there we will fetch the id
and populate records inside form.
I have already prepared code for UpdateCategory.vue
. Check these codes below you will understand how the axios is pulling the data from database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<template> <div> <form name="myform" @submit.prevent="UpdateCategory" id="myForm"> <input type="hidden" name="id" :value="singleCategory.id"> <div class="form-group"> <label for="category_name">Category Name</label> <input type="text" class="form-control" name="category_name" :value="singleCategory.category_title"> </div> <div class="form-group"> <label for="category_description">Category Description</label> <textarea name="category_description" id="" cols="30" rows="10" class="form-control">{{singleCategory.category_description}}</textarea> </div> <div class="form-group"> <button class="btn btn-primary btn-sm btn-flat" type="submit">Update Category</button> </div> </form> </div> </template> <script> export default { name: "UpdateCategory", props:['id'], data () { return { singleCategory : [], } }, methods : { getCategory() { let instance = this; axios.get('api/categories/'+instance.id+'/edit') .then(function (response) { instance.singleCategory = response.data; console.log("Success"); }) .catch(function (error) { console.log("Error"); }); }, UpdateCategory() { var formData = new FormData(document.getElementById("myForm")); let instance = this; axios.post('api/categories/edit', formData) .then(function (response) { instance.$router.push("/categories"); }) .catch(function (error) { console.log(error); }); } }, mounted () { this.getCategory(); } } </script> <style scoped> </style> |
Let prepare routes in laravel. Go to routes/api.php
and add these lines below.
1 2 |
Route::get("categories/{id}/edit",'CategoryController@editCategory'); Route::post("categories/edit",'CategoryController@updateCategory'); |
Add these new function into CategoryController.php
which is inside app/Http/Controllers
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public function editCategory($id) { $data = tbl_category::find($id); return Response::json($data); } public function updateCategory(Request $request) { $data = $request->all(); tbl_category::where("id",$data['id'])->update([ 'category_title'=>$data['category_name'], 'category_description'=>$data['category_description'] ]); return Response::json(true); } |
So this is it, Fire up php artisan serve
& npm run watch
and test the application.
This tutorial may seem little complicated compared to past other tutorials but no worries, you can always download full copy of this tutorial application at the end of this series.
Next : Laravel VueJS 2 CRUD Example Part 4 (Delete Records from Database)
Leave a Reply