PHPnews.io

Proof of Concept: Load any route into a modal with Inertia.js using Laravel and Vue.js

Written by Pascal Baljet Media - Blog / Original link on Mar. 25, 2021

Last month we started our second big project with Inertia.js. The development of the first one is well underway, and with the recent announcement of Server-Side Rendering support, I genuinely think Inertia is the future of web development. It's incredibly intuitive as it gives you the best of both worlds, Laravel for PHP development and Vue.js for front-end development.

As our pages become more complex, we found ourselves in need of loading forms in modals. In some cases, you don't want to redirect the user to a new page, but you want the user to stay on the current page and provide extra functionality with a modal.

Imagine a form to create a new product. Amongst the name, description, and price, you can also attach a category to it. But what if you want to attach a category that doesn't exist yet? We have a dedicated route and component to create new categories, but wouldn't it be great if you could re-use that functionality while the user stays on the product creation page?

You could take the shortcut. Build the category form for the second time, but now within a modal on the product creation page. On a large scale, this seems unmaintainable to me. Now we have to build and test two category creation forms.

The past few days, I took a deep dive in the Inertia source code and found a way to re-use existing routes and use them in a modal on another page. It's a very early draft, and it has its limitations, but I want to share it anyway.

Here's a small demo of Ping CRM. On the organizations' index page, there's a button to navigate to the creation page. I've added a second button that loads the same route into a modal.

On the contact creation page, you can select an organization. Here I've added the button as well. Note how the select dropdown instantly updated after I created the organization.

The installation of this package is quite simple. You need to add a Vue Component to your root template add some code to the Laravel middleware. For every route you want to open in a modal, you need to make a minor modification, but nothing else is required. You don't even have to touch your Laravel code!

You can find the source code and instructions at GitHub.

pascalbaljetmedia

« PHP Internals News: Episode 79: New in Initialisers - Vite with Laravel: Using TypeScript »