Laravel Array Helpers Every Developer Should Know About

Published on by

Laravel Array Helpers Every Developer Should Know About image

Laravel is known for its elegance, simplicity, and expressiveness. One of the most powerful features of Laravel is its helper functions. Laravel's array helpers are an essential tool for developers working with arrays of data.

This article will explore some Laravel array helper functions that every developer should know. These helpers can save time and make working with arrays more manageable. We'll cover join(), keyBy(), get(), first(), last(), and pluck(). So, let's dive in and see what Laravel's array helpers have to offer!

Array Join

You might be thinking, "why do I need this helper when I can use join() or implode()?"

use Illuminate\Support\Arr;
 
$stack = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];
 
Arr::join($stack, ', ');
// Tailwind, Alpine, Laravel, Livewire
 
implode($stack, ', ');
// Tailwind, Alpine, Laravel, Livewire

The above work exactly the same, so I'll leave it up to you to decide which style you prefer.

Where the join() helper really comes in handy is when you want the last value to use a separate joining string:

use Illuminate\Support\Arr;
 
$stack = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];
 
Arr::join($stack, ', ', ', and');
// Tailwind, Alpine, Laravel, and Livewire

Keyed Array data

Sometimes you'll take an array of data (i.e., multiple products) and key the data by a given product attribute. That way, you can conveniently target data for a given key.

You might have written something like the following, creating a new variable and stuffing the data into it by a keyed value:

$array = [
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
];
 
$keyed = [];
 
foreach ($array as $value) {
$keyed[$value['product_id']] = $value;
}
 
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/

Using the Arr::keyBy() method, you can do the same thing with one line of code:

$keyed = Arr::keyBy($array, 'product_id');

Checking and Getting Data from an Array

The mighty Arr::get() method is simple to use, but contains a powerful "dot notation" you can use to get nested data easily:

use Illuminate\Support\Arr;
 
$data = [
'products' => [
'desk' => [
'name' => 'Oakendesk'
'price' => 599.00,
'description' => 'Solid oak desk built from scratch.'
],
],
];
 
// 599.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]);

Getting the first or last element in an array

When you have an array and want to get the last element, you can reach for the end() function in PHP:

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

If your array is empty, though, you will get false instead:

$array = [];
end($array); // false

Using Laravel's last() helper, you have multiple options when an array is empty:

use Illuminate\Support\Arr;
 
$array = [];
 
Arr::last($array); // null
 
// Provide a default
Arr::last($array, null, 100); // 100

Using Laravel's helper also enables you to pass a closure as a second argument as the condition for which element to return first or last respectively:

$array = [100, 200, 300, 110];
 
Arr::last($array, fn ($e) => $e > 110); // 300
Arr::first($array, fn ($e) => $e > 110); // 200

Simple but powerful API for the many situations you might find yourself in with getting the first or last element within array data.

Plucking Data from an Array

Sometimes you need to get one scalar piece of data from a collection of data (i.e., emails from users):

$array = [
['user' => ['id' => 1, 'name' => 'User 1', 'email' => 'user1@example.com']],
['user' => ['id' => 2, 'name' => 'User 2', 'email' => 'user2@example.com']],
];
 
$emails = [];
 
foreach ($array as $result) {
$emails[] = $result['user']['email'];
}
 
/*
[
"user1@example.com",
"user2@example.com",
]
*/

Laravel's Arr::pluck() helper makes this trivial:

Arr::pluck($array, 'user.email');

Learn More

I hope you have seen a theme: helpers replace redundant tasks with expressive syntax. I believe they have a few other benefits: we can tap into the extra power some of these methods provide when needed (i.e. a closure condition in first() and last()), and it avoids temporary variables and loops that create mental overhead for repetitive things.

Though on the surface, function helpers in any language can seem redundant from using the built-in language features; however, I hope you've seen how powerful they can make redundant things you'll need to do in many of your applications. We've only scratched the surface of everything available in the Arr class. Sometimes we need simple array helpers, and other times you'll want the power of collections.

If you're new to the Laravel framework, check out the Helpers documentation to learn about all the useful string and array helpers at your fingertips in Laravel projects. Likely, you'll want these helpers in other PHP projects that aren't using Laravel too!

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Handling Geospatial Data with Laravel Magellan image

Handling Geospatial Data with Laravel Magellan

Read article
Managing Large Datasets in Laravel with LazyCollection image

Managing Large Datasets in Laravel with LazyCollection

Read article
Collect and Monitor Everything About Sent Emails in Your Laravel App image

Collect and Monitor Everything About Sent Emails in Your Laravel App

Read article
Packagist.org is ending support for Composer 1.x image

Packagist.org is ending support for Composer 1.x

Read article
Mastering Dynamic String Manipulation with Laravel's Str::replaceArray() image

Mastering Dynamic String Manipulation with Laravel's Str::replaceArray()

Read article
Laravel Jobs - December image

Laravel Jobs - December

Read article