Laravel Macro does rescue always.

Suman Shrestha
Jul 25, 2017 · 1 min read

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.

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.

Collection::macro('tr', function() {foreach($this->items as $tr){echo "<tr><td>{$tr->id}</td><td>{$tr->name}</td></tr>;}
});
Next time
$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.

laravelnepal

From laravel developers of nepal

Suman Shrestha

Written by

laravelnepal

From laravel developers of nepal

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade