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
You can use this
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
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
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 }}
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)