skip to Main Content

I need a screen to be accessed both by those who have logged in and by visitors, however I wanted to use auth()->user() on this page to access the data, however if I use the auth middleware it does not allow visitors on the page and if I Don’t use it, I can’t use auth()->user()

I’m doing a project for an online store and I made a main screen where it shows the products, the header showing the logo and if you haven’t logged in, a link to register or log in, but when I log in and I’m redirected to this main page, I don’t I can use auth()->user() to get the data, as the page does not have the auth:store middleware, and if I add this middleware the page is not accessed by visitors, I was thinking about using both middleware guest and auth together, but it didn’t work.

How could I solve my problem so that a page can be accessed both by those who are logged in and by visitors and be able to use auth()->user()?

2

Answers


  1. In a route without auth middleware return a blade view with code like this:

        @if(!empty(Auth::user()))
             <h1>USER {{ Auth::user()->id }}</h1>
        @else
            <h1>NO USER</h1>
        @endif
    

    If the user is authenticated (in another route), and then open this view, it will show the user id. If it’s not authenticated, will show "NO USER".

    Login or Signup to reply.
  2. auth()->user() does not require a restricted route.
    You can use it on any route.
    I would suggest using auth()->check() to determine if the user is logged in (i.e Not guest) and then you can do something like this.

    if (auth()->check()) {
        // code for logged in users only
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search