Reputation: 53
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.
Upvotes: 2
Views: 29335
Reputation: 5519
For Laravel 5.4 you can use:
@if(Auth::check())
// The user is authenticated...
@else
// The user is not authenticated...
@endif
For Laravel 5.5 and above:
@auth
// The user is authenticated...
@endauth
@guest
// The user is not authenticated...
@endguest
Upvotes: 8
Reputation: 492
also you can use the full class path of Auth in blade file like this
@if(\Illuminate\Support\Facades\Auth::check())
// code here
@endif
Upvotes: 0
Reputation: 53
Instead of using
<ul class="dropdown-menu">
<li><a href="{{ Auth::logout() }}">Logout</a></li>
</ul>
For log out, it is better to be codes as below, which is provided by official resources/view/layouts/app.php
<ul class="dropdown-menu">
<li>
<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
Upvotes: 2
Reputation: 2044
Update routes/web.php
file as
Route::group(['middleware' => 'web'], function () {
Route::get('/', 'CommonController@index');
Auth::routes();
}
Now to check auth in your blade template, you can use
@if(\Auth::check())
....
....
@else
....
....
@endif
Upvotes: 0