Latest

Thursday, July 13, 2017

Cannot use Auth::user() in blade template in Laravel 5.4

Asked by: Qilei Ren


I want to make my index page with both guest and auth functions.

When guests visit, they could try logging in; And after login, it will show the user's info such as username.

Below is what I did.

Routes are defined in routes/web.php:

Route::get('/', 'CommonController@index');
Auth::routes();

In blade template of index, I used Auth::user() to validate authentication but failed.

@if(Auth::user())
    <div id="user-panel">
        <a href="" class="user-panel-button">
            New Article
        </a>
        <div class="btn-group user-panel-button">
            <a type="button" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                {{ Auth::user()->name }} <span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
                <li><a href="{{ Auth::logout() }}">Logout</a></li>
            </ul>
        </div>
    </div>
@else
    <a href="{{ url('login') }}" class="button">
        Login
    </a>
@endif

Every time I logged in successfully, it will still show login button instead of user name button, after I REFRESH the index page.

I have checked session information, once I refreshed the page, the login_web_xxxxxxxxxxx session will be disappeared.

Furthermore, When I use Laravel default path for auth /home, it worked. Username could always be presented whatever how many times you refresh the page.

How should I fix this issue? Many thanks.



Source

No comments:

Post a Comment

Adbox