How to Use @auth Directive in Laravel Blade Templates
Use the
@auth directive in Laravel Blade templates to display content only when a user is logged in. Wrap the content inside @auth and @endauth tags to restrict it to authenticated users.Syntax
The @auth directive checks if a user is logged in. If yes, it shows the content inside it. Use @endauth to close the block.
You can also specify a guard like @auth('admin') to check authentication for a specific guard.
php
@auth
<!-- Content for logged-in users -->
@endauth
@auth('admin')
<!-- Content for logged-in admin users -->
@endauthExample
This example shows a welcome message only to logged-in users. Guests will not see this message.
blade
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Auth Directive Example</title> </head> <body> <h1>Welcome to Our Site</h1> @auth <p>Hello, {{ auth()->user()->name }}! You are logged in.</p> @endauth @guest <p>Please log in to see personalized content.</p> @endguest </body> </html>
Output
<h1>Welcome to Our Site</h1>
<p>Hello, John! You are logged in.</p>
Common Pitfalls
- Using
@authwithout a logged-in user will show nothing, which might confuse beginners expecting a fallback. - For guest users, use
@guestinstead of@auth. - Not closing the directive with
@endauthcauses syntax errors. - Specifying a guard incorrectly can cause the block to never show.
blade
@auth
<p>This shows only if logged in.</p>
<!-- Missing @endauth causes error -->
<!-- Correct usage -->
@auth
<p>This shows only if logged in.</p>
@endauthQuick Reference
Use @auth to show content to authenticated users and @guest for guests. Always close with @endauth or @endguest. You can specify guards like @auth('admin') to target specific user types.
| Directive | Purpose | Example |
|---|---|---|
| @auth | Show content if user is logged in | @auth ... @endauth |
| @auth('guard') | Show content if user logged in with specific guard | @auth('admin') ... @endauth |
| @guest | Show content if user is NOT logged in | @guest ... @endguest |
Key Takeaways
Use @auth and @endauth to wrap content for logged-in users only.
Specify guards in @auth('guard') to target different user types.
Always close @auth blocks with @endauth to avoid errors.
Use @guest for content visible only to guests (not logged in).
If no user is logged in, @auth content will not display.