Reputation:
I 'm using Laravel's middleware, and I'm trying to have an empty div if the user is not authenticated. Otherwise, I am trying to have a div that allows the user to create an account. I have tried the following:
@auth
<div class="form-group col-md-6"></div>
@else
<div class="form-group col-md-6">
<h6>Create Account</h6>
</div>
@endauth
Routes
Route::get('/checkout', 'CheckoutController@index')->name('checkout.index')->middleware('auth');
Route::get('/guestCheckout', 'CheckoutController@index')->name('guestCheckout.index');
CheckoutController.php
if (auth()->user() && request()->is('guestCheckout')) {
return redirect()->route('checkout.index');
}
The above does not work, and I have tried deleting the history, clearing caches, etc. but to no avail. Suggestions? Thank you!
Upvotes: 1
Views: 5388
Reputation: 100
The current (Laravel 8) way to do this is by using the Auth helper directives. https://laravel.com/docs/8.x/blade#authentication-directives
@auth
This only shows for logged in users
@endauth
@guest
This only shows for guests
@endguest
Upvotes: 0
Reputation: 33
You can Do it like this
<ul>
@guest
@if (Route::has('login'))
<li><a class="nav-link scrollto {{Request::url() === route('login') ? 'active' : ''}}" href="{{route('login')}}">Login</a></li>
@endif
@if (Route::has('register'))
<li><a class="nav-link scrollto {{Request::url() === route('register') ? 'active' : ''}}" href="{{route('register')}}">Register</a></li>
@endif
@else
<li class="dropdown"><a href="#"><span>{{ Auth::user()->name }}</span> <i class="bi bi-chevron-down"></i></a>
<ul>
<li>
<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">{{ __('Logout') }}</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
@csrf
</form>
</li>
</ul>
</li>
@endguest
</ul>
Upvotes: 0
Reputation: 1381
trying to have an empty div if user is not authenticated...
Your blade setup is really close. Try this!
@auth
<!-- the user is authenticated -->
<div class="form-group col-md-6>
</div>
@endauth <!-- note the end auth -->
@guest
<!-- the user is NOT authenticated -->
<div class="form-group col-md-6>
<h6>Create Account</h6>
</div>
@endguest
You can read up more about this here
As for your controller, try using:
if( Auth::check() )
{
// The user is authenticated..
} else {
// The user is NOT authenticated..
}
Upvotes: 3
Reputation: 28
There's out of the box way to do this!
@guest
<div class="form-group col-md-6>
</div>
@else
<div class="form-group col-md-6>
<h6>Create Account</h6>
</div>
@endguest
You don't need the middleware thingy if I were you.
Upvotes: 0