简体   繁体   中英

Laravel 5: Change navbar if user is logged

I'm completely new to Laravel, MVC and templating engines in general.

I need to show certain navbar buttons and options if a user is logged in such as: Notifications, Logout, Profile, etc... and a Login button otherwise.

Any help on how I could address this the right way is greatly appreciated. This is what I'm considering at the moment:

  • A User object is always passed to the view.
  • The view checks if the User is set (meaning it's logged in) to include the appropriate partial blade template for the navbar.

app.blade.php:

...
@if (isset($user))
     @include('partials.navbarlogged')

@else
     @include('partials.navbar')
...

Is this the best method? Thanks for your time!

If you are using Laravel 5's built in User model you can simply do

@if (Auth::check())
  //show logged in navbar
@else
  //show logged out navbar
@endif

New versions of Laravel (5.6 at time of writing) support these two directives in Blade:

@auth
// The user is authenticated...
@endauth

@guest
// The user is not authenticated...
@endguest

See official documentation here: https://laravel.com/docs/5.6/blade

For laravel 5.7 and above, use @auth and @guest directives.Here is the official documentation here

@auth
   // The user is authenticated...
@endauth
@guest
   // The user is not authenticated...
@endguest

You may specify the authentication guard that should be checked when using the @auth and @guest directives:

@auth('admin')
    // The user is authenticated...
@endauth

@guest('admin')
    // The user is not authenticated...
@endguest

Otherwise, you can use the @unless directive:

@unless (Auth::check())
    You are not signed in.
@endunless

You can also use Auth::guest()

The Auth::guest() method returns true or false.

Example -

@if (Auth::guest())
    <a href="{{ route('login') }}">Login</a>
    <a href="{{ route('register') }}">Register</a>
@else
    {{ Auth::user()->name }}
    <a href="{{ route('logout') }}">Logout</a>
@endif

Starting from Laravel 5.4 there's new blade directive @includeWhen which includes view based on a given boolean condition :

@includeWhen(Auth::check(), 'partials.navbarlogged')
@includeWhen(Auth::guest(), 'partials.navbar')

This should help :

@extends(Auth::check() ? 'partials.navbarlogged' : 'partials.navbar')

The Auth::chek() sees whether the user is logged in or not and returns a boolean.

If you are using Laravel 5's built-in User model you can simply do:

@if (Auth::check())
   //show logged in navbar
@else
   //show logged out navbar
@endif

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