Inertia is a new approach to building classic server-driven web apps. We call it the modern monolith.

Inertia allows you to create fully client-side rendered, single-page apps, without much of the complexity that comes with modern SPAs. It does this by leveraging existing server-side frameworks like Laravel.

Recently, I decided to use inertia for a project and to be honest, I love what Jonathan Reinink did on this project. I hope to send my support soon.

As stated on the official website, inertia does not have client-side routing. Meaning all your routing and validations are done from the server-side. In the case of Laravel, it plays so well.

Sharing data

Often times, you would love to access the logged-in user or some site configurations from any of your Vue components. Inertia completely got you covered.

The ::share() static method in the Inertia response object can be used to share data across all your Vue components as below:

    'authUser' => static function () {
         return [
           'roles' => Auth::user()->roles->pluck('name'),
           'permissions' => Auth::user()->permissions->pluck('name'),

Above is how you can share data with vue components. This should be done inside the AppServiceProvider.php or in a new service provider. If you prefer using a separate provider, don’t forget to register it in the app.php inside the config folder.

Accessing data in Vue components

Now that we’ve shared the data, we can access them in our components. These data are available as props through $page prop and merged together with other props.

Since page props and shared data are merged together, be sure to namespace your shared data appropriately.

Here is how you can access our permissions.

  v-if="! user.deleted_at 
  && $page.authUser.permissions.includes('delete users')"
    class="text-red-600 hover:underline" 
    tabindex="-1" type="button" @click="destroy">
    Delete User

Here, we are only allowing a user with the “delete users” permission to have access to the delete button.

You can see that we are accessing the permissions through the page prop and checking if the permissions this user has included “delete users”.

If that returns true, the user will be able to have access to the delete button. Note, authorizations need to be done at the server-side as well in case Javascript is deactivated on the browser.

This is where we end it on how to share data globally with your Vue components using Laravel and Inertia.

See you in the next episode. Cheers!

(Visited 955 times, 1 visits today)

Leave A Comment

Your email address will not be published. Required fields are marked *