Laravel Inertia renders data from backend to frontend
P粉342101652
P粉342101652 2024-03-27 00:09:22
0
1
364

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粉342101652
P粉342101652

reply all(1)
P粉771233336

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/

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!