Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, Inertia.js and vue, check if user is logged In

I'm using laravel and inertia.js to implement my project. In my navbar I want to display div element with some user details if the user is logged in. And if the user is not logged in the div should not appear. I have tried this but its not showing the details neither when I am logged in nor when I'm not. What should I do?

<div class="ml-3 relative" v-if="$page.props.auth.user">
    <div>
        <button @click="dropDown=true"
                class="bg-gray-800 flex text-sm rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white"
                id="user-menu" aria-haspopup="true">
            <span class="sr-only">Open user menu</span>
            <img class="h-8 w-8 rounded-full object-cover" :src="$page.props.user.profile_photo_url"
                 :alt="$page.props.user.name"/>
        </button>
    </div>
    <div v-if="dropDown"
         class="origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg py-1 bg-white ring-1 ring-black ring-opacity-5"
         role="menu" aria-orientation="vertical" aria-labelledby="user-menu">
        <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem">
            <form method="POST" @submit.prevent="logout">
                <jet-responsive-nav-link as="button">
                    Logout
                </jet-responsive-nav-link>
            </form>
        </a>
    </div>
</div>

On AppServiceProvider

public function boot()
{
    //check if user is logged in
    Inertia::share('auth.user', function() {
        return ['loggedIn' => Auth::check()];
    });
}
like image 407
josef Avatar asked Oct 19 '25 03:10

josef


1 Answers

With Inertia you can create a HandlerInertiaRequest Middlware. The HandleInertiaRequests middleware provides a "share" method where you can define the data that is automatically shared with each Inertia response. In Your case thats the user which is logged in.

You can find more infos in the docs Shared Data. They have an example in there demo app repository.

In your view you can check if the user is logged in by checking the shared data user prop.

v-if="$page.props.auth.user"
like image 145
Mo. Avatar answered Oct 21 '25 17:10

Mo.