简体   繁体   中英

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()];
    });
}

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"

I guess you can follow the same approach built here in this middleware, https://github.com/inertiajs/pingcrm/blob/master/app/Http/Middleware/HandleInertiaRequests.php and then you separated the logic from the providers

Laravel 8.4.0 with InertiaJS returns $page.props.user by default if user logged in (see this answer ). So you can simply do,

<element v-if="$page.props.user">This will only show when a user logged in.</element>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM