X
    Categories: PHP

Laravel vuejs form validation

Laravel vuejs form validation

Laravel Vuejs Form Validation. Here I will explain you, how to handle laravel validation errors with vue js. In this example we are going to see simple form validation with vue js. Here I have a table called messages which has two fields name and message. We are going to store the user messages with validation errors.

Step 1 : Create Route

Route::get('vue/form', 'VueController@index');
Route::post('vue/form', 'VueController@store');

Step 2 : Create Model with migration

php artisan make:model Message --migration

app/Message.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    protected $fillable = [
    'name',
    'message'
    ];
}

Migrate to Database :

class CreateMessagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('messages', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->nullable();
            $table->text('message')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('messages');
    }
}

Run : php artisan migrate

Step 3 : Create Controller :

php artisan make:controller VueController --resource

app/Http/Controllers/VueController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\MessageRequest;
use App\Message;

class VueController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('vue.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(MessageRequest $request)
    {
        return Message::create($request->all());
    }

}

Step 4 : Create blade file

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Vuejs Form</div>

                <div class="panel-body" id="app">
                        <form method="POST" action="http://localhost:8888/laravel54/public/vue/form" class="form-horizontal" @submit.prevent="onSubmit" >
                        {{ csrf_field() }}
                            <div :class="['form-group', errors.name ? 'has-error' : '']" >
                                <label >
Step 5 : Handle Form Validation
const app = new Vue({
    el: '#app',

    data: {
    	form: {
    		name : '',
    		message : '',
    	},
    	errors: [],
    	success : false,    
    },
    methods : {
    	onSubmit() {

    		formData = new FormData();
    		formData.append('name', this.form.name);
    		formData.append('message', this.form.message);

    		axios.post('http://localhost:8888/laravel54/public/vue/form', formData).then( response => {
    		    this.errors = [];
    		    this.form.name = '';
    		    this.form.message = '';
    		    this.success = true;
                            console.log(response);
	    	} ).catch((error) => {
	                 this.errors = error.response.data;
	                 this.success = false;
	                 console.log(this.errors);
	            });
    	}
    }
});

Output

Marimuthu: