DEV Community

Cover image for Dynamic Render Inertia from different file path in using Laravel
Harry
Harry

Posted on

Dynamic Render Inertia from different file path in using Laravel

I haven't written a blog post in a long time due to some personal issues. But today, I'm writing about how to dynamically render your Vue files inertia from different folder paths in inertia.

Before going to actual topic let's me example what is inertia. Inertia is a framework that makes it easy to build modern single-page applications with Laravel. Inertia works by sending data from your server-side controller to your client-side JavaScript application as props. These props can then be used in your client-side view components to display data or update the UI. By default inertia render app.blade.php as root file but you can modified it. Okay!!Let's go to actual topic.

This blog post is for someone who is facing this for the first time when they start working on Inertia. Here are the steps you need to follow.

Step 1

In your app.js inside resources/js

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'

createInertiaApp({
  resolve: name => {
    //here below two lines you need to make some changes
    const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
    return pages[`./Pages/${name}.vue`]
  },
  setup({ el, App, props, plugin }) {
    createApp({ render: () => h(App, props) })
      .use(plugin)
      .mount(el)
  },
})
Enter fullscreen mode Exit fullscreen mode

Step 2

You have to modified like this.


import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'

createInertiaApp({
  resolve: name => {
    //here below two lines you need to make some changes
    // name means full file path of your vue's file location
    const page = await import(`../../${name}.vue`,{
                eager: true,
            })
return page.default;
  },
  setup({ el, App, props, plugin }) {
    createApp({ render: () => h(App, props) })
      .use(plugin)
      .mount(el)
  },
})

Enter fullscreen mode Exit fullscreen mode

Step 3

You have have to pass your **vue** path from controller as below



namespace Src\ModuleName\User\Presentation\HTTP;

use Inertia\Inertia;
use App\Http\Controllers\Controller;


class UserController extends Controller
{

    public function index()
    { 
     //full path of your vue file path you need to configure
     return Inertia::render('src/ModuleName/User/Presentation/Resources/Index'); 
   }

}

Enter fullscreen mode Exit fullscreen mode

I am give my screenshot of my folder structure .As below

Image description

If you have any questions about this topic, please feel free to leave a comment below or on my twitter handle @hareom284. I'm always happy to help!. Happy to share your though. Thanks for reading!

Top comments (0)