However, if you’re trying to swap two items of an associative array, this can be little bit more hands-on. So, in this short post, I’ll show you how you can use macros in Laravel to keep your code looking clean and reusable. By the end of the p ost, you should have a brief idea on how to create a macro that you can use to change the order of your like in this example: In Laravel, macros are methods that can be added to classes at runtime.
This is the macro that we’re going to be adding: So, let’s add this macro to the service provider so that we can access it: Now that we’ve defined the macro inside the service provider, we can swap items in arrays using the Arr::swap() method. Here are some examples below of how we would be able to use this method: Hopefully, this short post will have given you a very brief overview of how to quickly create a macro that we can use swap two items in a PHP array.