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:
1$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)
:
1>>> $u = \App\User::create([ 2 'name' => 'Admin', 3 'email' => 'admin@example.com', 4 'password' => bcrypt('secret') 5]); 6>>> (array) $u 7=> [ 8 "\0*\0fillable" => [ 9 "name",10 "email",11 "password",12 ],13 "\0*\0hidden" => [14 "password",15 "remember_token",16 ],17 "\0*\0connection" => "mysql",18 "\0*\0table" => "users",19 "\0*\0primaryKey" => "id",20 "\0*\0keyType" => "int",21 "incrementing" => true,22 "\0*\0with" => [],23 "\0*\0withCount" => [],24 "\0*\0perPage" => 15,25 "exists" => true,26 "wasRecentlyCreated" => true,27 "\0*\0attributes" => [28 "name" => "Admin",29 "email" => "admin@example.com",30 "password" => "$2y$10$LtI7hHc.eZQi9BcU61Qp3eTXliFrBq03Lav1QpLlDFvBNbsPYklYS",31 "updated_at" => "2018-11-28 23:14:40",32 "created_at" => "2018-11-28 23:14:40",33 "id" => 1,34 ],35 ....36 ]
Here’s how array_wrap()
treats the same value:
1>>> array_wrap($u) 2=> [ 3 App\User {#2897 4 name: "Admin", 5 email: "admin@example.com", 6 updated_at: "2018-11-28 23:14:40", 7 created_at: "2018-11-28 23:14:40", 8 id: 1, 9 },10 ]
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:
1/** 2 * If the given value is not an array and not null, wrap it in one. 3 * 4 * @param mixed $value 5 * @return array 6 */ 7public static function wrap($value) 8{ 9 if (is_null($value)) {10 return [];11 }1213 return is_array($value) ? $value : [$value];14}
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
:
1/** 2 * Set the affected Eloquent model and instance ids. 3 * 4 * @param string $model 5 * @param int|array $ids 6 * @return $this 7 */ 8public function setModel($model, $ids = []) 9{10 $this->model = $model;11 $this->ids = Arr::wrap($ids);1213 $this->message = "No query results for model [{$model}]";1415 if (count($this->ids) > 0) {16 $this->message .= ' '.implode(', ', $this->ids);17 } else {18 $this->message .= '.';19 }2021 return $this;22}
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.
Filed in:
Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.