Source: ashallendesign-uk.medium.com

How to Swap Items in an Array Using Laravel Macros

Category: Laravel, Laravel, PHP, PHP

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.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners