Vue.js/Laravel: pass category id to Vue.js component

Viewed 156

I'm using Vue.js with Laravel and facing a problem. I want to pass category id from the blade file to the Vue.js component as a prop. But don't know what is good practice and the right way for this.

I've defined the route something like this:

Route::view('/categories/{category}/edit', 'edit')->name('categories.edit');

and my edit.blade.php file is:

@extends('master')

@section('vue')
    <div id="app">
        <categories-edit :id=""></categories-edit>
    </div>
@endsection

The Vue.js component code is:

<template>
    <div class="container py-5">
        <div class="row">
            <div class="col-lg-12">
                <div class="mb-3">
                    <label for="name" class="form-label">Name:</label>
                    <input type="text" v-model="formState.name" name="name" class="form-control" id="name" placeholder="Category Name" autocomplete="off">
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
   name: 'CategoriesEdit',
   props: ['id'],
   data: function () {
       return {
           formState: {
               name: '',
               photo: ''
           }
       }
   },
    mounted() {
       
    },
    methods: {
      loadInitialData: function () {
          const self = this;
          axios.get(``).then(function (response) {
          }).catch(function (err) {

          });
      }
   }

}
</script>

When I'm entering the URL in the web browser. I'm getting this error.

http://example.test/categories/1/edit

Output:

Undefined variable $category
1 Answers

Since you are using Route::view() you do not have the traditional way of getting route parameters and pass them to the view. Luckily you can always get these on the request object and there is a request() helper that makes it easier for Blade views.

<categories-edit :id="{{ request()->route('category') }}"></categories-edit>
Related