首页 > 解决方案 > How to save category in laravel 5.7 with vue.js

问题描述

Using Laravel 5.7 with vuejs, I am trying to display parent_id from a MySQL categories table. I want to pass the name and get all it's child categories irrespective of the parent.

My blade

<form action="{{ route('categories.store') }}" method="post">
    @csrf
    <div class="form-group">
        <label for="name">name:</label>
        <input type="text" id="name" class="form-control" v-model="name">
    </div>
    <div class="form-group">
        <label for="sub_category">category</label>
        <select id="sub_category" v-model="parent_id" class="form-control">
            <option data-display="main category" value="0">main category</option>
            <option v-for="category in categories" :value="category.id">@{{ category.name }}</option>
        </select>
    </div>
    <div class="form-group">
        <button type="button" @click="addCategory()"  class="btn btn-info">save</button>
    </div>
</form>

web.php

Route::group(['namespace' => 'Admin', 'prefix' => 'admin'],function (){
    $this->get('panel', 'PanelController@index')->name('panel.index');
    $this->resource('categories', 'CategoryController');
});

My vue

addCategory: function () {
    axios.post(route('categories.store'), {
        name: this.name,
        parent_id: this.parent_id,
    }).then(response => {
        this.categories.push({'name': response.data.name, 'id': response.data.id});
    }, response => {
        this.error = 1;
        console.log('Errors');
    });
}

CategoryController

public function store(Request $request)
{
    $category = new Category();
    $category->name = $request->name;
    $category->parent_id = $request->parent_id;
    if ($category->save()) {
        return $category;
    }
}

I see this error in console for first

Vue js

Too

VVue

And I get 405 error.

405 error

标签: vue.jslaravel-5.7

解决方案


  1. @click从提交按钮中删除。
  2. 从表单操作中删除路线...并设置它#
  3. 添加@submit="addCategory()"到表单
  4. axios.post示例中添加没有路由功能的路由。

更新: 如果要防止页面刷新,请.prevent@submit.


推荐阅读