CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   JAVA   Laravel VueJS 2 CRUD Tutorial Part 3 (Update Data Into Datab ...

Laravel VueJS 2 CRUD Tutorial Part 3 (Update Data Into Database)

March 17, 2018 by SNK

Laravel VueJS Tutorial Part 4

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.

tbl_categories.php
PHP
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.

List of Dummy Data Prepared for VueJS 2 Update Operation

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 :

  1. Get all the records from database.
  2. Click the record we want to edit.
  3. Populate it in the form.
  4. 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.vueand 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.

routes.js
JavaScript
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

ViewCategory
1
<a class="btn btn-default btn-xs">Edit Category</a>

to this line:

ViewCategory
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.

UpdateCategory.vue
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.

api.php
PHP
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

CategoryController.php
PHP
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)

SHARE ON
Buffer

Enjoyed this article?

Like us on

JAVA Javascript laravel vue js crud tutorial part 3 vuejs crud example vuejs crud tutorial vuejs crud update data into database

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.