Insane Laravel blade tip
Welcome Laravelians ,
This blade tip is insane for me so I wanna tell you what Im doing ,
For some reason the blade looping directives is not always the best choice , because it has some helper methods and properties which you can use like $loop & first() & last() .. you know ,
You don’t always need this helpers in your loop so here is a trick I’m doing it in any of my Laravel projects ,
So the trick is that um creating a new blade directive and call it ( @loop ) for example or you can call it anything you love,
So for example instead of add the Blade::directive() function into the AppServiceProvider , Im creating new service provider for all my blade directives so lets do this run this command for creating new service provider
php artisan make:provider BladeDirectiveServiceProvider
Now in your new service provider you’d notice that there is the default two methods “ register() & boot() “
So now lets dig into the boot method and define our new ( @loop ) directive
Now after creating our new directive lets register it in our config/app.php and go to “ providers ” group and register the new directive like :
<?php
'providers' => [
// .....
App\Providers\BladeDirectiveServiceProvider::class
]
Now you can go to any of your blade file and loop through array with our new blade directive
@loop($users as $user)
// Manipulating data
@endloop
Thanks Laravelians and wait for another awesome articles ❤