0
0
LaravelHow-ToBeginner · 3 min read

How to Use @guest in Blade Templates in Laravel

In Laravel Blade templates, use the @guest directive to display content only to users who are not logged in. It works as a conditional block that runs when no user is authenticated, ending with @endguest.
📐

Syntax

The @guest directive starts a block that shows content only if the user is not logged in. You close this block with @endguest. Inside this block, you can put any HTML or Blade code you want to show to guests.

blade
@guest
    <!-- Content for guests only -->
@endguest
💻

Example

This example shows a message only to users who are not logged in. If a user is logged in, this message will not appear.

blade
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Guest Example</title>
</head>
<body>
    @guest
        <p>Welcome, guest! Please <a href="/login">log in</a> to access more features.</p>
    @endguest

    @auth
        <p>Welcome back, {{ auth()->user()->name }}!</p>
    @endauth
</body>
</html>
Output
<p>Welcome, guest! Please <a href="/login">log in</a> to access more features.</p>
⚠️

Common Pitfalls

  • Using @guest without closing it with @endguest causes Blade errors.
  • Confusing @guest with @auth which shows content only to logged-in users.
  • Trying to use @guest outside Blade templates or in plain PHP files won't work.
blade
@guest
    <p>This is for guests only.</p>
<!-- Missing @endguest causes error -->

<!-- Correct usage -->
@guest
    <p>This is for guests only.</p>
@endguest
📊

Quick Reference

@guest shows content only if no user is logged in. Use @endguest to close the block. For logged-in users, use @auth and @endauth.

DirectivePurpose
@guest ... @endguestShow content only to guests (unauthenticated users)
@auth ... @endauthShow content only to authenticated users
auth()->check()Check if user is logged in in PHP code
auth()->guest()Check if user is not logged in in PHP code

Key Takeaways

Use @guest in Blade to show content only to users who are not logged in.
Always close @guest blocks with @endguest to avoid errors.
Use @auth for content meant only for logged-in users.
@guest works only inside Blade templates, not in plain PHP files.
Combine @guest and @auth to customize views based on user login status.