7 Laravel Array Helper Functions That Will Save You Time

What is a Helper Function in PHP & Laravel?

A Helper function is a small piece of code that performs a specific task or operation and can be used anywhere in your application. A helper function usually comes in handy if you want to add a feature to your Laravel application that can be used at multiple locations within your controllers, views, or model files. These functions can be considered as global functions.

How to create Helper functions in Laravel?

To create a helper function in Laravel, you need to create a new PHP file and specify the file path in the composer.json file. To learn more about creating helper functions in Laravel, please check this article.

Laravel Array Helper Functions:

Laravel is known for its elegance, simplicity, and expressiveness. One of the most powerful features of Laravel is its helper functions. Laravel provides many useful helper functions for interacting and manipulating array data structures. Laravel’s array functions offer additional functionality on top of PHP’s built-in array functions.

In this article, we will explore some useful Laravel array helper functions that every developer should know. These helpers can save time and make working with arrays more manageable. We will cover the following array helper functions in this blog post:

  • join()
  • keyBy()
  • get()
  • first()
  • last()
  • pluck()

1. Array Join(Arr::join())

The Arr::join method joins array elements with a string. Using this method’s second argument, you may also specify the joining string for the final element of the array:

use Illuminate\Support\Arr;
 
$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];
 

$joined = Arr::join($array, ', '); 
// Tailwind, Alpine, Laravel, Livewire
 

$joined = Arr::join($array, ', ', ' and ');
// Tailwind, Alpine, Laravel and Livewire

2. Keyed Array Data(Arr::keyBy())

The Arr::keyBy method keys the array by the given key. If multiple items have the same key, only the last one will appear in the new array:

use Illuminate\Support\Arr;
 
$array = [
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
];
 
$keyed = Arr::keyBy($array, 'product_id');
 
/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

3. Getting Data from an Array(Arr::get())

The Arr::get method retrieves a value from a deeply nested array using “dot” notation:

use Illuminate\Support\Arr;
 
// Define a nested array 
$data = [
    'products' => [
        'desk' => [
            'name' => 'Oakendesk'
            'price' => 499.00,
            'description' => 'Solid oak desk built from scratch.'
        ],
    ],
];
 

// Returnd price i.e. 499.00
Arr::get($data, 'products.desk.price');
 
// Returns false
Arr::has($data, 'products.desk.discount');
 
// Returns null
Arr::get($data, 'products.desk.discount');
 
// Returns custom default value if not found.
Arr::get($data, 'products.desk.discount', ['type' => 'percent', 'value' => 10]);

The Arr::get method also accepts a default value, which will be returned if the specified key is not present in the array:

use Illuminate\Support\Arr;
 
$discount = Arr::get($array, 'products.desk.discount', 0);
 
// Output
// 0

4. Getting the First or Last element from an Array

To get the last element of an array, you can either use the PHP’s built-in end() function or Laravel’s Arr::last() function.

Using the end() function:

$array = [100, 200, 300, 110];
 
end($array);  // 110

If the array is empty, a false value will be returned.

$array = [];

end($array);  // false

Using Laravel’s last() helper function:

use Illuminate\Support\Arr;
 
$array = [];
 
Arr::last($array);  // null

Using Laravel’s helper also enables you to pass a closure as a second argument as the condition. The last or first element of the array is returned based on this condition’s result as below:

use Illuminate\Support\Arr;
 
$array = [100, 200, 300, 110];
 
$last = Arr::last($array, function (int $value, int $key) {
    return $value >= 150;
});
 
// 300


// Using PHP arrow functions notation
Arr::last($array, fn ($e) => $e > 110);  // 300
Arr::first($array, fn ($e) => $e > 110);  // 200

A default value may also be passed as the third argument to the method. This value will be returned if no value passes the truth test:

use Illuminate\Support\Arr;
 
$array = [];


Arr::last($array); // null

Arr::last($array, $callback, $default);
 
// Provide a default
Arr::last($array, null, 100);  // 100

Frequently Asked Questions

To create a Helper function in Laravel, create a new PHP file and add it’s path to composer.json file

To create a Helper function in Laravel, create a new PHP file and add it’s path to composer.json file

Leave a Comment