Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mozew's avatar
Level 6

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

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example-component', require('./components/ExampleComponent.vue'));

const app = new Vue({
    el: '#app',
    data: {
        name: "",
        parent_id: "",
        categories: [],
    },
    methods: {
        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 get 404 error.

0 likes
22 replies
zymawy's avatar

###Are You Saving It Or Retrieving It?

mozew's avatar
Level 6

NO, I'm Not Saving It Or Retrieving It?

Jaytee's avatar

Are you using the ziggy package to allow you to use route() in JS? If not, that's why you'd be getting the error because axios doesn't have a valid endpoint.

mozew's avatar
Level 6

I see this error in console for first

Vue js

Too

VVue

mozew's avatar
Level 6

I want to display categories in select option.

mozew's avatar
Level 6

I tried but I get 405 error. and I changed axios.post('categories/store', {....

405 error

signar's avatar

@irankhosravi I'm wondering about the same thing as @jaytee. How can you write this:

axios.post(route('categories.store'), {

Do you have a JavaScript method called route? If not that's your first error. I don't understand really what you are trying to achieve because you already have the parent id when posting a new category and could query for the parent using that if you don't want to return the newly created category.

realrandyallen's avatar

Looks like you’re mixing Vue directly into a Blade file - that’s why you’re receiving the error in the console - you need to put all your Vue code into a component and utilize that component in your blade file

Cronix's avatar

As mentioned, you're mixing php and javascript, which you can't do. They are different languages.

axios.post(route('categories.store'), {

axios.post() is javascript and route('categories.store') is php.

realrandyallen's avatar

@IRANKHOSRAVI - No it would be more like

axios.post('/categories/create', {
...

It depends on what your route is which you can find by running php artisan route:list

But honestly even if you got that part right it still wouldn’t work - there are multiple issues that still need to be fixed

signar's avatar

@irankhosravi try this in your Vue file:

axios.post('/categories'), {

If this doesn't work please report back with the error (screenshot or something)

mozew's avatar
Level 6

I tried replace axios.post('/categories'), { But that did not work.

enter image description here enter image description here enter image description here enter image description here

mozew's avatar
Level 6

I tried to save a category but failed. But you can help me.

realrandyallen's avatar
Level 44

Here's how you'd typically set all this up:

app.js

...

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key)))


const app = new Vue({
    el: '#app'
});

...

/resources/js/components/Categories.vue

<template>
    <div>
        <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>
    </div>
</template>

<script>
    export default {
        data() {
            return { 
                name: "",
                parent_id: "",
                categories: [],
            }
        },

        methods: {
            addCategory() {
                const self = this;

                axios.post('categories', {
                    name: self.name,
                    parent_id: self.parent_id,
                }).then((response) => {
                    self.categories.push(response.data.category);
                }).catch((response) => {
                    self.error = 1;
                    console.log('Errors');
                });
            }
        },
    }
</script>

some-view.blade.php

<div>
    <categories></categories>
</div>

CategoryController.php

public function store(Request $request)
{
      $category = Category::create($request->all());

      if ($request->wantsJson()) {
         return response()->json(['message' => 'Category Created', 'category' => $category], 200);
      }

      return redirect()->route('categories.show', $category->id);
}
1 like
mozew's avatar
Level 6

Thanks for answer.

Just another problem: it does not show up after the browser is refreshed.

I wrote that code in

<option v-for="category in categories" :value="category.id">@{{ category.name }}</option>

Is it correct?

realrandyallen's avatar

@IRANKHOSRAVI - You need to feed the component the categories that exist in the database in order for them to show...so:

CategoryController.php / index function or whatever function you're using

public function index()
{
      $categories = Category::all();

      return view('whatever-view-youre-using', compact('categories'));
}

whatever-view-youre-using.blade.php

<div>
    <categories :data="{{ $categories }}"></categories>
</div>

Categories.vue

...

<script>
export default {
    props: ['data'],

    data() {
        return { 
            name: "",
            parent_id: "",
            categories: this.data,
        }
     },

...

</script>
1 like

Please or to participate in this conversation.