Home > OS >  How to return data from the controller using InertiaJS
How to return data from the controller using InertiaJS

Time:06-14

This is my ProductController

public function index()
{
  return Product::all();
}

I'm looking a way to return this method from an Inertia request to my Vue component, This is the way I tried this,

routes/web.php

Route::get('/', function () {
  return Inertia::render('App', [ProductController::class, 'index']);
});

And here is my Vue component (Not the exact one the way I'm trying to get the data)

<template>

</template>

<script>
props: {
  index: Array,
},
</script>

CodePudding user response:

In your controller, you can pass the list of your products to your component doing:

public function index()
{
  return Inertia::render('App', [
    'products' => Product::all()
  ]);
}

Doc: https://inertiajs.com/responses

Then declare your route like:

Route::get('/products', [ProductController::class, 'index']);

This will create a /products route that will point to the index action of your controller that will return the list of products to your component.

And in your component, you can access the products:

<template>
  <div>
    {{ products.length }}
  </div>
</template>

<script>
props: {
  products: Array,
},
</script>
  • Related