DEV Community

Cover image for 3 Quick Tips about Laravel Blade.
Francisco Campos
Francisco Campos

Posted on

3 Quick Tips about Laravel Blade.

Hello, today i have three random quick tips about blade maybe some of you will know them, maybe some of you will learn one or two new things, and let's begin...

1 - forelse loop

What do you do when you need to show a loop in Blade with foreach, but the list might be empty? You probably write if-else statement around it, right?

Using foreach

@if ($users->count())
  @foreach ($users as $user)
    <li>{{ $user->name }}</li>
  @endforeach
@else
   <p>No users.</p>
@endif
Enter fullscreen mode Exit fullscreen mode

You can use this

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse
Enter fullscreen mode Exit fullscreen mode

2 - auth and guest

The auth and guest directives may be used to quickly determine if the current user is authenticated or is a guest.

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

@guest
    // The user is not authenticated...
@endguest
Enter fullscreen mode Exit fullscreen mode

3 - auth()->user() Object

auth user object is accessible throughout all blade files without really passing them, so logged user can be accessed by our auth user.

User-name: {{ auth()->user()->name }}
User-email: {{ auth()->user()->email }}
Enter fullscreen mode Exit fullscreen mode

So, you don't need to pass anything from the controller to view the information or check the information of logged user.

Thanks for reading.
Laravel Docs
Laravel Blade
My twitter

Top comments (0)