laravel vue.js ajaxでformを送信し、validate

ajaxした時に 422 コードが返ってくるが、仕様なのでバグじゃない。



```web.php

Route::get('hoge/form', 'HogeController@index');
Route::post('hoge/form', 'HogeController@store');

```


```HogeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Log;


class HogeController extends Controller
{
    public function index()
    {
//        vuejs-form を使うよ
        return view('vuejs-form');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'comments' => 'required'
        ]);

//        AJAXリクエストにvalidateメソッドを使う場合、Laravelはリダイレクトレスポンスを生成しません。代わりにバリデーションエラーを全部含んだJSONレスポンスを生成します。このJSONレスポンスは422 HTTPステータスコードで送られます。

        return response()->json(['success'=>'Done!']);
    }
}

```


```vuejs-form.blade.php

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel-Vue-todo</title>
    <style type="text/css">
        /*初期表示時にテンプレートが一瞬表示されてしまうのを防ぐ*/
        [v-cloak] {
            display: none;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-8 col-sm-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Simple Vuejs Form Validation with Laravel - ItSolutionStuff.com</div>


                <div class="panel-body" id="app">
                    <form method="POST" action="/vuejs/form" class="form-horizontal" @submit.prevent="onSubmit" >
                        {{ csrf_field() }}
                        <div :class="['form-group', allerros.name ? 'has-error' : '']" >
                            <label for="name" class="col-sm-4 control-label">Name</label>
                            <div class="col-sm-6">
                                <input id="name" name="name" value=""  autofocus="autofocus" class="form-control" type="text" v-model="form.name">
                                <span v-if="allerros.name" :class="['label label-danger']">@{{ allerros.name[0] }}</span>
                            </div>
                        </div>
                        <div :class="['form-group', allerros.comments ? 'has-error' : '']" >
                            <label for="comments" class="col-sm-4 control-label">Message</label>
                            <div class="col-sm-6">
                                <input id="comments" name="comments"  class="form-control" type="comments" v-model="form.comments">
                                <span v-if="allerros.comments" :class="['label label-danger']">@{{ allerros.comments[0] }}</span>
                            </div>
                        </div>
                        <span v-if="success" :class="['label label-success']">Record submitted successfully!</span>
                        <button type="submit" class="btn btn-primary">
                            Send
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>



<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/heyui"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/heyui/themes/index.css">


<script type="text/javascript">
    const app = new Vue({
        el: '#app',
        data: {
            form: {
                name : '',
                comments : '',
            },
            allerros: [],
            success : false,
        },
        methods : {
            onSubmit() {


                dataform = new FormData();
                dataform.append('name', this.form.name);
                dataform.append('comments', this.form.comments);

                axios.post('/hoge/form/',dataform).then( response => {
                    this.allerros = [];
                    this.form.name = '';
                    this.form.comments = '';
                    this.success = true;
                } ).catch((error) => {
                    this.allerros = error.response.data.errors;
                    this.success = false;
                });
            }
        }
    });
</script>

</body>
</html>

```