Vue Multiple Checkboxes Example Tutorial

Vue Multiple Checkboxes Example Tutorial is today’s topic. You can use the v-model directive to create two-way data bindings on form input, textarea, and select elements. It automatically picks the correct way to update the component based on the input type. The v-model will ignore the initial valuechecked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth.

Vue Multiple Checkboxes Example Tutorial

First, create a new Vue.js project using Vue CLI using the following command.

#1: Create Vue.js project using Vue CLI.

Type the following command.

vue create mulcheckbox

 

Vue Multiple Checkboxes Example Tutorial

Now, go into the project folder and install the bootstrap css framework.

npm install bootstrap --save

# or

yarn add bootstrap

Import the Bootstrap CSS file inside src >> main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'

import 'bootstrap/dist/css/bootstrap.min.css';

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

#2: Create a form in App.vue component.

Okay, now we will use bootstrap css classes to construct the form as well as its input types. In our case, it is a checkbox. Write the following code inside src >> App.vue file.

<template>
  <div id="app" class="container">
    <h2>Vue Multiple Checkbox Example</h2>
    <form @submit.prevent="send()">
      <div class="form-group">
        <div class="form-check">
          <label for="joe" class="form-check-label">
            <input type="checkbox" 
                    id="joe" 
                    class="form-check-input"
                    value="joe" 
                    v-model="checkedNames" />            
            Joe
          </label>
        </div>
       <div class="form-check">
          <label for="jack" class="form-check-label">
            <input type="checkbox" 
                    id="jack" 
                    class="form-check-input"
                    value="jack" 
                    v-model="checkedNames" />            
            Jack
          </label>
        </div>
        <div class="form-check">
          <label for="Nick" class="form-check-label">
            <input type="checkbox" 
                    id="nick" 
                    class="form-check-input"
                    value="nick" 
                    v-model="checkedNames">            
            Nick
          </label>
        </div>
        <br>
      </div>
      <div class="form-group">
        <button class="btn btn-info">Submit</button>
      </div>
    </form>
  </div>
</template>

<script>

export default {
  data() {
    return {
      checkedNames: []
    }
  },
  methods: {
    send() {
      console.log(this.checkedNames.toString());
    }
  }
}
</script>

So, here, we have implemented three checkboxes. Each checkbox has its unique label, id, and value. We have used the two-way data binding with the help of v-model.

So, when the user checks the input values, it will add that value in an Array. If the user checks any checkbox, it will push that checkbox value into the checkedNames array.

When the user submits the form, we get all the checked items and convert that array into the string. So, we can directly store that values in the database.

 

Vue checkbox example tutorial

#3: Install axios library and send values to a server.

Type the following command to install vue-axios and axios promise based library.

npm install vue-axios axios --save

# or

yarn add axios vue-axios

Add these libraries in the main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

import 'bootstrap/dist/css/bootstrap.min.css';

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

Now, write the send function inside App.vue file to send the data to the server.

<template>
  <div id="app" class="container">
    <h2>Vue Multiple Checkbox Example</h2>
    <form @submit.prevent="send()">
      <div class="form-group">
        <div class="form-check">
          <label for="joe" class="form-check-label">
            <input type="checkbox" 
                    id="joe" 
                    class="form-check-input"
                    value="joe" 
                    v-model="checkedNames" />            
            Joe
          </label>
        </div>
       <div class="form-check">
          <label for="jack" class="form-check-label">
            <input type="checkbox" 
                    id="jack" 
                    class="form-check-input"
                    value="jack" 
                    v-model="checkedNames" />            
            Jack
          </label>
        </div>
        <div class="form-check">
          <label for="Nick" class="form-check-label">
            <input type="checkbox" 
                    id="nick" 
                    class="form-check-input"
                    value="nick" 
                    v-model="checkedNames">            
            Nick
          </label>
        </div>
        <br>
      </div>
      <div class="form-group">
        <button class="btn btn-info">Submit</button>
      </div>
    </form>
  </div>
</template>

<script>

export default {
  data() {
    return {
      checkedNames: []
    }
  },
  methods: {
    send() {
      let obj = {
        check_items: this.checkedNames
      }
      this.axios.post('http://localhost:8000/api/checks', obj)
          .then(res => console.log(res.data));
    }
  }
}
</script>

I have taken the server: localhost:8000. You need to put what you are using. Then we need to put /api/ checks because we will use api.php instead of web.php route file.

#4: Setup Laravel Backend API

Install the Laravel 5.7 using the following command.

laravel new api

# or

composer create-project laravel/laravel api --prefer-dist

Now, we need to connect the Laravel with MySQL database. So write the credentials inside the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your db
DB_USERNAME=your username
DB_PASSWORD=your password

Now, create a model, migration, and controller using the following command.

php artisan make:model Check -m
php artisan make:controller CheckController

Write the following schema inside [timestamps]create.checks.php file.

public function up()
{
        Schema::create('checks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('check_items');
            $table->timestamps();
        });
}

Now, migrate the database using the following command.

php artisan migrate

Next step is to write the route inside routes >> api.php file.

// api.php

Route::post('checks', 'CheckController@store');

Now, code the store function to save the data from the axios request and send a response.

<?php

// CheckController.php

namespace App\Http\Controllers;
use App\Check;

use Illuminate\Http\Request;

class CheckController extends Controller
{
    public function store(Request $request)
    {
      $check = new Check;
      $items = implode(",", $request->get('check_items'));
      $check->check_items = $items;

      $check->save();

      return response()->json('Your values has been saved');
    }
}

#5: Handle CORS problem

We need to add one more laravel package called laravel-cors. It will handle the  Cross-Origin Resource Sharing. So, let us install using the following command.

composer require barryvdh/laravel-cors

 

 

laravel vue example

Now, include the  group api middleware inside App >> Http >> Kernel.php file.

'api' => [
     'throttle:60,1',
     'bindings',
     \Barryvdh\Cors\HandleCors::class,
],

Save the file and you are done.

#6: Send the data to the server

Go to the Vue development server: http://localhost:8080/. Check the box and send the post data to the Laravel API server. You can see the MySQL database.

 

laravel multiple values example

Also, you can see in the browser console that, we have successfully saved the values.

Finally, Vue Multiple Checkboxes Example Tutorial is over.

Tags:,

Add a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.