HighSolutions's avatar

Laravel routes with Vue

Hi,

Is there a better way to pass route ID variable than this from code below? I am using Laravel API and fetching it in Vue.

API routes

// List single product
Route::get('product/{id}', 'ProductController@show');

Web.php

Route::get('/product/{product}', 'MainController@show')->name('product.show');

MainController@show

// Show product details page

    public function show(Product $product) {
        return view('product', ['product' => $product]);
    }

So i am using Implicit Binding and Model key is Id

Passing id to vue my way

<product id="{{ $product->id }}"></product>

Fetching product with given Id

<script>
    export default {
        props: ['id'],
        data() {
            return {
                product: {
                    id: '',
                    title: '',
                    slug: '',
                    price: '',
                    description: '',
                    image: ''
                },
                pagination: {},
                edit: false
            };
        },

        created() {
            this.fetchProduct(this.id);
        },

        methods: {
            fetchProduct(id) {
                let vm = this;
                fetch('/api/product/' + id)
                    .then(res => res.json())
                    .then(res => {
                        this.product = res.data;
                    })
                    .catch(err => console.log(err));
            }
        }
    }
</script>
0 likes
1 reply
AhimbisibweRoland's avatar

I would probably pass a finished route url if I had nothing else to do with the id since you are already using named routes.

<product data-url="{{route('products.show',$product) }}"></product>

Please or to participate in this conversation.