Helpers
Introduction
Laravel includes a variety of global "helper" PHP functions. Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient.
Available Methods
Arrays & Objects
Arr::accessible Arr::add Arr::collapse Arr::crossJoin Arr::divide Arr::dot Arr::except Arr::exists Arr::first Arr::flatten Arr::forget Arr::get Arr::has Arr::hasAny Arr::isAssoc Arr::isList Arr::join Arr::keyBy Arr::last Arr::map Arr::mapSpread Arr::mapWithKeys Arr::only Arr::pluck Arr::prepend Arr::prependKeysWith Arr::pull Arr::query Arr::random Arr::set Arr::shuffle Arr::sort Arr::sortDesc Arr::sortRecursive Arr::take Arr::toCssClasses Arr::toCssStyles Arr::undot Arr::where Arr::whereNotNull Arr::wrap data_fill data_get data_set data_forget head last
Numbers
Number::abbreviate Number::clamp Number::currency Number::fileSize Number::forHumans Number::format Number::ordinal Number::pairs Number::percentage Number::spell Number::trim Number::useLocale Number::withLocale
Paths
app_path base_path config_path database_path lang_path mix public_path resource_path storage_path
URLs
action asset route secure_asset secure_url to_route url
Miscellaneous
abort abort_if abort_unless app auth back bcrypt blank broadcast cache class_uses_recursive collect config context cookie csrf_field csrf_token decrypt dd dispatch dispatch_sync dump encrypt env event fake filled info literal logger method_field now old once optional policy redirect report report_if report_unless request rescue resolve response retry session tap throw_if throw_unless today trait_uses_recursive transform validator value view with
Arrays & Objects
Arr::accessible()
The Arr::accessible
method determines if the given value is array accessible:
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);
// true
$isAccessible = Arr::accessible(new Collection);
// true
$isAccessible = Arr::accessible('abc');
// false
$isAccessible = Arr::accessible(new stdClass);
// false
Arr::add()
The Arr::add
method adds a given key / value pair to an array if the given key doesn't already exist in the array or is set to null
:
use Illuminate\Support\Arr;
$array = Arr::add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
Arr::collapse()
The Arr::collapse
method collapses an array of arrays into a single array:
use Illuminate\Support\Arr;
$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Arr::crossJoin()
The Arr::crossJoin
method cross joins the given arrays, returning a Cartesian product with all possible permutations:
use Illuminate\Support\Arr;
$matrix = Arr::crossJoin([1, 2], ['a', 'b']);
/*
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]
*/
$matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']);
/*
[
[1, 'a', 'I'],
[1, 'a', 'II'],
[1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
*/
Arr::divide()
The Arr::divide
method returns two arrays: one containing the keys and the other containing the values of the given array:
use Illuminate\Support\Arr;
[$keys, $values] = Arr::divide(['name' => 'Desk']);
// $keys: ['name']
// $values: ['Desk']
Arr::dot()
The Arr::dot
method flattens a multi-dimensional array into a single level array that uses "dot" notation to indicate depth:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
$flattened = Arr::dot($array);
// ['products.desk.price' => 100]
Arr::except()
The Arr::except
method removes the given key / value pairs from an array:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100];
$filtered = Arr::except($array, ['price']);
// ['name' => 'Desk']
Arr::exists()
The Arr::exists
method checks that the given key exists in the provided array:
use Illuminate\Support\Arr;
$array = ['name' => 'John Doe', 'age' => 17];
$exists = Arr::exists($array, 'name');
// true
$exists = Arr::exists($array, 'salary');
// false
Arr::first()
The Arr::first
method returns the first element of an array passing a given truth test:
use Illuminate\Support\Arr;
$array = [100, 200, 300];
$first = Arr::first($array, function (int $value, int $key) {
return $value >= 150;
});
// 200
A default value may also be passed as the third parameter to the method. This value will be returned if no value passes the truth test:
use Illuminate\Support\Arr;
$first = Arr::first($array, $callback, $default);
Arr::flatten()
The Arr::flatten
method flattens a multi-dimensional array into a single level array:
use Illuminate\Support\Arr;
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$flattened = Arr::flatten($array);
// ['Joe', 'PHP', 'Ruby']
Arr::forget()
The Arr::forget
method removes a given key / value pair from a deeply nested array using "dot" notation:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::forget($array, 'products.desk');
// ['products' => []]
Arr::get()
The Arr::get
method retrieves a value from a deeply nested array using "dot" notation:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
$price = Arr::get($array, 'products.desk.price');
// 100
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);
// 0
Arr::has()
The Arr::has
method checks whether a given item or items exists in an array using "dot" notation:
use Illuminate\Support\Arr;
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
$contains = Arr::has($array, 'product.name');
// true
$contains = Arr::has($array, ['product.price', 'product.discount']);
// false
Arr::hasAny()
The Arr::hasAny
method checks whether any item in a given set exists in an array using "dot" notation:
use Illuminate\Support\Arr;
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
$contains = Arr::hasAny($array, 'product.name');
// true
$contains = Arr::hasAny($array, ['product.name', 'product.discount']);
// true
$contains = Arr::hasAny($array, ['category', 'product.discount']);
// false
Arr::isAssoc()
The Arr::isAssoc
method returns true
if the given array is an associative array. An array is considered "associative" if it doesn't have sequential numerical keys beginning with zero:
use Illuminate\Support\Arr;
$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
// true
$isAssoc = Arr::isAssoc([1, 2, 3]);
// false
Arr::isList()
The Arr::isList
method returns true
if the given array's keys are sequential integers beginning from zero:
use Illuminate\Support\Arr;
$isList = Arr::isList(['foo', 'bar', 'baz']);
// true
$isList = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]);
// false
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
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'],
]
*/
Arr::last()
The Arr::last
method returns the last element of an array passing a given truth test:
use Illuminate\Support\Arr;
$array = [100, 200, 300, 110];
$last = Arr::last($array, function (int $value, int $key) {
return $value >= 150;
});
// 300
A default value may 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;
$last = Arr::last($array, $callback, $default);
Arr::map()
The Arr::map
method iterates through the array and passes each value and key to the given callback. The array value is replaced by the value returned by the callback:
use Illuminate\Support\Arr;
$array = ['first' => 'james', 'last' => 'kirk'];
$mapped = Arr::map($array, function (string $value, string $key) {
return ucfirst($value);
});
// ['first' => 'James', 'last' => 'Kirk']
Arr::mapSpread()
The Arr::mapSpread
method iterates over the array, passing each nested item value into the given closure. The closure is free to modify the item and return it, thus forming a new array of modified items:
use Illuminate\Support\Arr;
$array = [
[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9],
];
$mapped = Arr::mapSpread($array, function (int $even, int $odd) {
return $even + $odd;
});
/*
[1, 5, 9, 13, 17]
*/
Arr::mapWithKeys()
The Arr::mapWithKeys
method iterates through the array and passes each value to the given callback. The callback should return an associative array containing a single key / value pair:
use Illuminate\Support\Arr;
$array = [
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john@example.com',
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane@example.com',
]
];
$mapped = Arr::mapWithKeys($array, function (array $item, int $key) {
return [$item['email'] => $item['name']];
});
/*
[
'john@example.com' => 'John',
'jane@example.com' => 'Jane',
]
*/
Arr::only()
The Arr::only
method returns only the specified key / value pairs from the given array:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
$slice = Arr::only($array, ['name', 'price']);
// ['name' => 'Desk', 'price' => 100]
Arr::pluck()
The Arr::pluck
method retrieves all of the values for a given key from an array:
use Illuminate\Support\Arr;
$array = [
['developer' => ['id' => 1, 'name' => 'Taylor']],
['developer' => ['id' => 2, 'name' => 'Abigail']],
];
$names = Arr::pluck($array, 'developer.name');
// ['Taylor', 'Abigail']
You may also specify how you wish the resulting list to be keyed:
use Illuminate\Support\Arr;
$names = Arr::pluck($array, 'developer.name', 'developer.id');
// [1 => 'Taylor', 2 => 'Abigail']
Arr::prepend()
The Arr::prepend
method will push an item onto the beginning of an array:
use Illuminate\Support\Arr;
$array = ['one', 'two', 'three', 'four'];
$array = Arr::prepend($array, 'zero');
// ['zero', 'one', 'two', 'three', 'four']
If needed, you may specify the key that should be used for the value:
use Illuminate\Support\Arr;
$array = ['price' => 100];
$array = Arr::prepend($array, 'Desk', 'name');
// ['name' => 'Desk', 'price' => 100]
Arr::prependKeysWith()
The Arr::prependKeysWith
prepends all key names of an associative array with the given prefix:
use Illuminate\Support\Arr;
$array = [
'name' => 'Desk',
'price' => 100,
];
$keyed = Arr::prependKeysWith($array, 'product.');
/*
[
'product.name' => 'Desk',
'product.price' => 100,
]
*/
Arr::pull()
The Arr::pull
method returns and removes a key / value pair from an array:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100];
$name = Arr::pull($array, 'name');
// $name: Desk
// $array: ['price' => 100]
A default value may be passed as the third argument to the method. This value will be returned if the key doesn't exist:
use Illuminate\Support\Arr;
$value = Arr::pull($array, $key, $default);
Arr::query()
The Arr::query
method converts the array into a query string:
use Illuminate\Support\Arr;
$array = [
'name' => 'Taylor',
'order' => [
'column' => 'created_at',
'direction' => 'desc'
]
];
Arr::query($array);
// name=Taylor&order[column]=created_at&order[direction]=desc
Arr::random()
The Arr::random
method returns a random value from an array:
use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 4 - (retrieved randomly)
You may also specify the number of items to return as an optional second argument. Note that providing this argument will return an array even if only one item is desired:
use Illuminate\Support\Arr;
$items = Arr::random($array, 2);
// [2, 5] - (retrieved randomly)
Arr::set()
The Arr::set
method sets a value within a deeply nested array using "dot" notation:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::set($array, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]
Arr::shuffle()
The Arr::shuffle
method randomly shuffles the items in the array:
use Illuminate\Support\Arr;
$array = Arr::shuffle([1, 2, 3, 4, 5]);
// [3, 2, 5, 1, 4] - (generated randomly)
Arr::sort()
The Arr::sort
method sorts an array by its values:
use Illuminate\Support\Arr;
$array = ['Desk', 'Table', 'Chair'];
$sorted = Arr::sort($array);
// ['Chair', 'Desk', 'Table']
You may also sort the array by the results of a given closure:
use Illuminate\Support\Arr;
$array = [
['name' => 'Desk'],
['name' => 'Table'],
['name' => 'Chair'],
];
$sorted = array_values(Arr::sort($array, function (array $value) {
return $value['name'];
}));
/*
[
['name' => 'Chair'],
['name' => 'Desk'],
['name' => 'Table'],
]
*/
Arr::sortDesc()
The Arr::sortDesc
method sorts an array in descending order by its values:
use Illuminate\Support\Arr;
$array = ['Desk', 'Table', 'Chair'];
$sorted = Arr::sortDesc($array);
// ['Table', 'Desk', 'Chair']
You may also sort the array by the results of a given closure:
use Illuminate\Support\Arr;
$array = [
['name' => 'Desk'],
['name' => 'Table'],
['name' => 'Chair'],
];
$sorted = array_values(Arr::sortDesc($array, function (array $value) {
return $value['name'];
}));
/*
[
['name' => 'Table'],
['name' => 'Desk'],
['name' => 'Chair'],
]
*/
Arr::sortRecursive()
The Arr::sortRecursive
method recursively sorts an array using the sort
function for numerically indexed sub-arrays and the ksort
function for associative sub-arrays:
use Illuminate\Support\Arr;
$array = [
['Roman', 'Taylor', 'Li'],
['PHP', 'Ruby', 'JavaScript'],
['one' => 1, 'two' => 2, 'three' => 3],
];
$sorted = Arr::sortRecursive($array);
/*
[
['JavaScript', 'PHP', 'Ruby'],
['one' => 1, 'three' => 3, 'two' => 2],
['Li', 'Roman', 'Taylor'],
]
*/
If you would like the results sorted in descending order, you may use the Arr::sortRecursiveDesc
method.
$sorted = Arr::sortRecursiveDesc($array);
Arr::take()
The Arr::take
method returns a new array with the specified number of items:
use Illuminate\Support\Arr;
$array = [0, 1, 2, 3, 4, 5];
$chunk = Arr::take($array, 3);
// [0, 1, 2]
You may also pass a negative integer to take the specified number of items from the end of the array:
$array = [0, 1, 2, 3, 4, 5];
$chunk = Arr::take($array, -2);
// [4, 5]
Arr::toCssClasses()
The Arr::toCssClasses
method conditionally compiles a CSS class string. The method accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression. If the array element has a numeric key, it will always be included in the rendered class list:
use Illuminate\Support\Arr;
$isActive = false;
$hasError = true;
$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError];
$classes = Arr::toCssClasses($array);
/*
'p-4 bg-red'
*/
Arr::toCssStyles()
The Arr::toCssStyles
conditionally compiles a CSS style string. The method accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression. If the array element has a numeric key, it will always be included in the rendered class list:
use Illuminate\Support\Arr;
$hasColor = true;
$array = ['background-color: blue', 'color: blue' => $hasColor];
$classes = Arr::toCssStyles($array);
/*
'background-color: blue; color: blue;'
*/
This method powers Laravel's functionality allowing merging classes with a Blade component's attribute bag as well as the @class
Blade directive.
Arr::undot()
The Arr::undot
method expands a single-dimensional array that uses "dot" notation into a multi-dimensional array:
use Illuminate\Support\Arr;
$array = [
'user.name' => 'Kevin Malone',
'user.occupation' => 'Accountant',
];
$array = Arr::undot($array);
// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]
Arr::where()
The Arr::where
method filters an array using the given closure:
use Illuminate\Support\Arr;
$array = [100, '200', 300, '400', 500];
$filtered = Arr::where($array, function (string|int $value, int $key) {
return is_string($value);
});
// [1 => '200', 3 => '400']
Arr::whereNotNull()
The Arr::whereNotNull
method removes all null
values from the given array:
use Illuminate\Support\Arr;
$array = [0, null];
$filtered = Arr::whereNotNull($array);
// [0 => 0]
Arr::wrap()
The Arr::wrap
method wraps the given value in an array. If the given value is already an array it will be returned without modification:
use Illuminate\Support\Arr;
$string = 'Laravel';
$array = Arr::wrap($string);
// ['Laravel']
If the given value is null
, an empty array will be returned:
use Illuminate\Support\Arr;
$array = Arr::wrap(null);
// []
data_fill()
The data_fill
function sets a missing value within a nested array or object using "dot" notation:
$data = ['products' => ['desk' => ['price' => 100]]];
data_fill($data, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 100]]]
data_fill($data, 'products.desk.discount', 10);
// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]
This function also accepts asterisks as wildcards and will fill the target accordingly:
$data = [
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2'],
],
];
data_fill($data, 'products.*.price', 200);
/*
[
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2', 'price' => 200],
],
]
*/
data_get()
The data_get
function retrieves a value from a nested array or object using "dot" notation:
$data = ['products' => ['desk' => ['price' => 100]]];
$price = data_get($data, 'products.desk.price');
// 100
The data_get
function also accepts a default value, which will be returned if the specified key is not found:
$discount = data_get($data, 'products.desk.discount', 0);
// 0
The function also accepts wildcards using asterisks, which may target any key of the array or object:
$data = [
'product-one' => ['name' => 'Desk 1', 'price' => 100],
'product-two' => ['name' => 'Desk 2', 'price' => 150],
];
data_get($data, '*.name');
// ['Desk 1', 'Desk 2'];
The {first}
and {last}
placeholders may be used to retrieve the first or last items in an array:
$flight = [
'segments' => [
['from' => 'LHR', 'departure' => '9:00', 'to' => 'IST', 'arrival' => '15:00'],
['from' => 'IST', 'departure' => '16:00', 'to' => 'PKX', 'arrival' => '20:00'],
],
];
data_get($flight, 'segments.{first}.arrival');
// 15:00
data_set()
The data_set
function sets a value within a nested array or object using "dot" notation:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]
This function also accepts wildcards using asterisks and will set values on the target accordingly:
$data = [
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2', 'price' => 150],
],
];
data_set($data, 'products.*.price', 200);
/*
[
'products' => [
['name' => 'Desk 1', 'price' => 200],
['name' => 'Desk 2', 'price' => 200],
],
]
*/
By default, any existing values are overwritten. If you wish to only set a value if it doesn't exist, you may pass false
as the fourth argument to the function:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200, overwrite: false);
// ['products' => ['desk' => ['price' => 100]]]
data_forget()
The data_forget
function removes a value within a nested array or object using "dot" notation:
$data = ['products' => ['desk' => ['price' => 100]]];
data_forget($data, 'products.desk.price');
// ['products' => ['desk' => []]]
This function also accepts wildcards using asterisks and will remove values on the target accordingly:
$data = [
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2', 'price' => 150],
],
];
data_forget($data, 'products.*.price');
/*
[
'products' => [
['name' => 'Desk 1'],
['name' => 'Desk 2'],
],
]
*/
head()
The head
function returns the first element in the given array:
$array = [100, 200, 300];
$first = head($array);
// 100
last()
The last
function returns the last element in the given array:
$array = [100, 200, 300];
$last = last($array);
// 300