Laravel has always been amazing to me on how much we can make stuffs for ourselves. Not just coding, but implementing functions that are useful to application too.
Macro is the one the best feature, developer adore in this framework.
Imagine you retrieve data from eloquent model like Model::all(). Here, You did not retrieve a single instance, you retrieved collection.
So, now you need to do something with it.
Let’s say you are looping over and printing values over tr and td combination in a table.
1 2 3 | foreach($collection as $tr){ echo "<tr><td>{$tr->id}</td><td>{$tr->name}</td></tr>; } |
You will hate it when you have to do this every time.
So, to use macro here would be useful.
1 2 3 4 5 6 7 8 | Collection::macro('tr', function() { foreach($this->items as $tr){ echo "<tr><td>{$tr->id}</td><td>{$tr->name}</td></tr>; } }); |
Next time
1 | $collection->tr(); |
is enough.
Better yet those “id” and “name” can also be passed as function arguments. But, we can do optimization as we like.
Everything is awesome.
Be First to Comment