Unwrapping array_wrap()

Published on by

Unwrapping array_wrap() image

Laravel has a wrap method and array_wrap() helper to normalize values into an array. Raul @rcubitto shared this nice tip about it on Twitter and before seeing his Tweet I wasn’t aware of this method:

Did you know about the array\_wrap function? Nice little wrapper for a snippet we've all written at least once in our lives #Laravel pic.twitter.com/Pg3zFJhxzO

— Raul (@rcubitto) June 22, 2017

I noticed that some people asked in response to Raul’s tweet why that was needed vs. casting to an array:

$value = (array) $value;

Typecasting works for primitive values, but “iterables” get treated differently. For example, let’s say you want to allow a user to pass either one Eloquent model or an array of models. Here’s what happens when you try to cast a single model to an array with (array):

>>> $u = \App\User::create([
'name' => 'Admin',
'email' => 'admin@example.com',
'password' => bcrypt('secret')
]);
>>> (array) $u
=> [
"\0*\0fillable" => [
"name",
"email",
"password",
],
"\0*\0hidden" => [
"password",
"remember_token",
],
"\0*\0connection" => "mysql",
"\0*\0table" => "users",
"\0*\0primaryKey" => "id",
"\0*\0keyType" => "int",
"incrementing" => true,
"\0*\0with" => [],
"\0*\0withCount" => [],
"\0*\0perPage" => 15,
"exists" => true,
"wasRecentlyCreated" => true,
"\0*\0attributes" => [
"name" => "Admin",
"email" => "admin@example.com",
"password" => "$2y$10$LtI7hHc.eZQi9BcU61Qp3eTXliFrBq03Lav1QpLlDFvBNbsPYklYS",
"updated_at" => "2018-11-28 23:14:40",
"created_at" => "2018-11-28 23:14:40",
"id" => 1,
],
....
]

Here’s how array_wrap() treats the same value:

>>> array_wrap($u)
=> [
App\User {#2897
name: "Admin",
email: "admin@example.com",
updated_at: "2018-11-28 23:14:40",
created_at: "2018-11-28 23:14:40",
id: 1,
},
]

The helper documentation states “If the given value is not an array and not null, wrap it in one.” and looks like this at the time of writing:

/**
* If the given value is not an array and not null, wrap it in one.
*
* @param mixed $value
* @return array
*/
public static function wrap($value)
{
if (is_null($value)) {
return [];
}
 
return is_array($value) ? $value : [$value];
}

How is this helper useful?

As stated, the helper takes care of null values and returns an empty array when the value is null. Laravel has various places in the framework where you can pass an array of values or a single value. Normalizing like this makes for a nice API and Laravel takes care of creating a consistent array behind the scenes.

Here’s an example of setting the model on the ModelNotFoundException class using Arr::wrap:

/**
* Set the affected Eloquent model and instance ids.
*
* @param string $model
* @param int|array $ids
* @return $this
*/
public function setModel($model, $ids = [])
{
$this->model = $model;
$this->ids = Arr::wrap($ids);
 
$this->message = "No query results for model [{$model}]";
 
if (count($this->ids) > 0) {
$this->message .= ' '.implode(', ', $this->ids);
} else {
$this->message .= '.';
}
 
return $this;
}

The wrap method is found in the Arr class (Illuminate\Support\Arr) which has an accompanying array_wrap helper function you can use in Laravel apps.

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.

image
Laravel Forge

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

Visit Laravel Forge
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
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

Bespoke software solutions built for your business. We ♥ Laravel

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
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with Vue and Livewire stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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
Rector logo

Rector

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

Rector

The latest

View all →
Running a Single Test, Skipping Tests, and Other Tips and Tricks image

Running a Single Test, Skipping Tests, and Other Tips and Tricks

Read article
View Third-party Relations in model:show - Now Available in Laravel 11.11 image

View Third-party Relations in model:show - Now Available in Laravel 11.11

Read article
Asserting a JSON Response Structure in Laravel image

Asserting a JSON Response Structure in Laravel

Read article
Backpack turns 8 years old, celebrates with 40% discount image

Backpack turns 8 years old, celebrates with 40% discount

Read article
Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4 image

Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4

Read article
Neovim Plugin to for Navigating Laravel and Livewire Components image

Neovim Plugin to for Navigating Laravel and Livewire Components

Read article