How to return data from the controller using InertiaJS

Issue

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>

Solution

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>

Answered By – Jedupont

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published