Laravel blade auth and guest


The @auth directive in Laravel Blade is used to conditionally display content based on whether the user is authenticated. It allows you to show or hide sections of your Blade views depending on the user's authentication status. This is useful for customizing the user experience based on their login state.

How @auth Works

When using the @auth directive, Blade checks if the user is authenticated. If the user is authenticated, the content inside the @auth block is rendered. If the user is not authenticated, the content is not displayed.

Basic Usage

Example:

@auth <p>Welcome back, {{ Auth::user()->name }}!</p> @endauth

In this example, the message will only be displayed if the user is logged in. Auth::user() is used to get the currently authenticated user, allowing you to access user information.

Using @guest Directive

The @guest directive is the opposite of @auth. It is used to display content when the user is not authenticated.

Example:

@guest <p>Please log in to access more features.</p> @endguest

In this example, the message will be shown to users who are not logged in.

Combining @auth and @guest

You can use @auth and @guest together to tailor content based on the user's authentication status.

Example:

@auth <p>Welcome back, {{ Auth::user()->name }}!</p> @else <p>Please log in to access more features.</p> @endauth

Here, authenticated users see a welcome message, while non-authenticated users are prompted to log in.

Accessing Authenticated User Data

Within the @auth block, you can use the Auth facade or the auth() helper to access information about the authenticated user.

Example:

@auth <p>Logged in as: {{ Auth::user()->email }}</p> <p>Member since: {{ Auth::user()->created_at->format('F j, Y') }}</p> @endauth

In this example, the email and membership date of the authenticated user are displayed.

Alternative: Using Blade Components

For more complex cases or when you want to include reusable pieces of UI based on authentication, you might use Blade components or include partials.

Example:

In a Blade component file (resources/views/components/user-info.blade.php):

@auth <div class="user-info"> <p>Welcome back, {{ Auth::user()->name }}!</p> </div> @endauth

Using the component:

<x-user-info />

Summary

The @auth directive in Laravel Blade is a convenient way to conditionally display content based on whether a user is authenticated. By using @auth, you can render user-specific information and functionality when a user is logged in, while using @guest allows you to provide alternative content for non-authenticated users. This directive helps tailor the user experience according to authentication status, enhancing the functionality and security of your application.