Home  >  Q&A  >  body text

Laravel Inertia renders data from backend to frontend

Using ReactJS with Laravel Inertia is brand new.

I'm trying to render data from the database to the frontend. I use controller to get data from database...

// Show all main categories
public static function index() {
    return MainCategory::all(['main_category_id', 'main_category_name']);
}

Then use web.php to pass it to the frontend via the following code.

Route::get('/', function () {
   return Inertia::render('Admin/Categories', [
        'categories' => MainCategoryController::index()
   ]);
})->name('admin.category-setup');

I currently don’t know how to call categories on the front end using reactjs. How can I do this?

P粉342101652P粉342101652230 days ago406

reply all(1)I'll reply

  • P粉771233336

    P粉7712333362024-03-27 13:18:35

    I sometimes use Inertia's built-in usePage-Hook for React to access passed props. This comes in handy when you are using shared data that is accessible to all front-end components (https:///inertiajs.com/shared-data). As long as your backend (Laravel) code is working properly and the actual categories-Property is handed over to the category component or shared for all frontends, you can do the following:

    import React from 'react';    
    import { usePage } from '@inertiajs/inertia-react';
        
        function App() {
            const categories = usePage().props.categories;
        
            return (
                
      {categories.map((category) => (
    • {category}
    • ))}
    ); }
    However, the most common approach for me is to simply give the same variable names that are passed into Inertia-Component in Laravel into React-Component-Props, as shown below. In my opinion this should fit your use case perfectly:

    import React from 'react';    
        
        function App({categories}) {        
            return (
                
      {categories.map((category) => (
    • {category}
    • ))}
    ); }

    If you want to learn more about Inertia, I highly recommend reading the documentation. The developers do a great job of explaining everything so that inexperienced Laravel and React Devs can understand what's going on. It's really not very readable, but shows some interesting functionality: https://inertiajs.com/

    reply
    0
  • Cancelreply