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::add Arr::collapse Arr::divide Arr::dot Arr::except Arr::first Arr::flatten Arr::forget Arr::get Arr::has Arr::last Arr::only Arr::pluck Arr::prepend Arr::pull Arr::random Arr::set Arr::sort Arr::sortRecursive Arr::where Arr::wrap data_fill data_get data_set head last
Paths
app_path base_path config_path database_path mix public_path resource_path storage_path
Strings
__ class_basename e preg_replace_array Str::after Str::before Str::camel Str::contains Str::containsAll Str::endsWith Str::finish Str::is Str::kebab Str::limit Str::orderedUuid Str::plural Str::random Str::replaceArray Str::replaceFirst Str::replaceLast Str::singular Str::slug Str::snake Str::start Str::startsWith Str::studly Str::title Str::uuid Str::words trans trans_choice
URLs
action asset route secure_asset secure_url url
Miscellaneous
abort abort_if abort_unless app auth back bcrypt blank broadcast cache class_uses_recursive collect config cookie csrf_field csrf_token dd decrypt dispatch dispatch_now dump encrypt env event factory filled info logger method_field now old optional policy redirect report request rescue resolve response retry session tap throw_if throw_unless today trait_uses_recursive transform validator value view with
Method Listing
Arrays & Objects
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::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::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 ($value, $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 specific key is not found:
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::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 ($value, $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::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::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::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::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 the given Closure:
use Illuminate\Support\Arr;
$array = [
['name' => 'Desk'],
['name' => 'Table'],
['name' => 'Chair'],
];
$sorted = array_values(Arr::sort($array, function ($value) {
return $value['name'];
}));
/*
[
['name' => 'Chair'],
['name' => 'Desk'],
['name' => 'Table'],
]
*/
Arr::sortRecursive()
The Arr::sortRecursive
method recursively sorts an array using the sort
function for numeric sub-arrays and ksort
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'],
]
*/
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 ($value, $key) {
return is_string($value);
});
// [1 => '200', 3 => '400']
Arr::wrap()
The Arr::wrap
method wraps the given value in an array. If the given value is already an array it will not be changed:
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;
$nothing = null;
$array = Arr::wrap($nothing);
// []
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'];
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 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:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200, false);
// ['products' => ['desk' => ['price' => 100]]]
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
Paths
app_path()
The app_path
function returns the fully qualified path to the app
directory. You may also use the app_path
function to generate a fully qualified path to a file relative to the application directory:
$path = app_path();
$path = app_path('Http/Controllers/Controller.php');
base_path()
The base_path
function returns the fully qualified path to the project root. You may also use the base_path
function to generate a fully qualified path to a given file relative to the project root directory:
$path = base_path();
$path = base_path('vendor/bin');
config_path()
The config_path
function returns the fully qualified path to the config
directory. You may also use the config_path
function to generate a fully qualified path to a given file within the application's configuration directory:
$path = config_path();
$path = config_path('app.php');
database_path()
The database_path
function returns the fully qualified path to the database
directory. You may also use the database_path
function to generate a fully qualified path to a given file within the database directory:
$path = database_path();
$path = database_path('factories/UserFactory.php');
mix()
The mix
function returns the path to a versioned Mix file:
$path = mix('css/app.css');
public_path()
The public_path
function returns the fully qualified path to the public
directory. You may also use the public_path
function to generate a fully qualified path to a given file within the public directory:
$path = public_path();
$path = public_path('css/app.css');
resource_path()
The resource_path
function returns the fully qualified path to the resources
directory. You may also use the resource_path
function to generate a fully qualified path to a given file within the resources directory:
$path = resource_path();
$path = resource_path('sass/app.scss');
storage_path()
The storage_path
function returns the fully qualified path to the storage
directory. You may also use the storage_path
function to generate a fully qualified path to a given file within the storage directory:
$path = storage_path();
$path = storage_path('app/file.txt');
Strings
__()
The __
function translates the given translation string or translation key using your localization files:
echo __('Welcome to our application');
echo __('messages.welcome');
If the specified translation string or key does not exist, the __
function will return the given value. So, using the example above, the __
function would return messages.welcome
if that translation key does not exist.
class_basename()
The class_basename
function returns the class name of the given class with the class' namespace removed:
$class = class_basename('Foo\Bar\Baz');
// Baz
e()
The e
function runs PHP's htmlspecialchars
function with the double_encode
option set to true
by default:
echo e('<html>foo</html>');
// <html>foo</html>
preg_replace_array()
The preg_replace_array
function replaces a given pattern in the string sequentially using an array:
$string = 'The event will take place between :start and :end';
$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);
// The event will take place between 8:30 and 9:00
Str::after()
The Str::after
method returns everything after the given value in a string:
use Illuminate\Support\Str;
$slice = Str::after('This is my name', 'This is');
// ' my name'
Str::before()
The Str::before
method returns everything before the given value in a string:
use Illuminate\Support\Str;
$slice = Str::before('This is my name', 'my name');
// 'This is '
Str::camel()
The Str::camel
method converts the given string to camelCase
:
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// fooBar
Str::contains()
The Str::contains
method determines if the given string contains the given value (case sensitive):
use Illuminate\Support\Str;
$contains = Str::contains('This is my name', 'my');
// true
You may also pass an array of values to determine if the given string contains any of the values:
use Illuminate\Support\Str;
$contains = Str::contains('This is my name', ['my', 'foo']);
// true
Str::containsAll()
The Str::containsAll
method determines if the given string contains all array values:
use Illuminate\Support\Str;
$containsAll = Str::containsAll('This is my name', ['my', 'name']);
// true
Str::endsWith()
The Str::endsWith
method determines if the given string ends with the given value:
use Illuminate\Support\Str;
$result = Str::endsWith('This is my name', 'name');
// true
Str::finish()
The Str::finish
method adds a single instance of the given value to a string if it does not already end with the value:
use Illuminate\Support\Str;
$adjusted = Str::finish('this/string', '/');
// this/string/
$adjusted = Str::finish('this/string/', '/');
// this/string/
Str::is()
The Str::is
method determines if a given string matches a given pattern. Asterisks may be used to indicate wildcards:
use Illuminate\Support\Str;
$matches = Str::is('foo*', 'foobar');
// true
$matches = Str::is('baz*', 'foobar');
// false
Str::kebab()
The Str::kebab
method converts the given string to kebab-case
:
use Illuminate\Support\Str;
$converted = Str::kebab('fooBar');
// foo-bar
Str::limit()
The Str::limit
method truncates the given string at the specified length:
use Illuminate\Support\Str;
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);
// The quick brown fox...
You may also pass a third argument to change the string that will be appended to the end:
use Illuminate\Support\Str;
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
// The quick brown fox (...)
Str::orderedUuid()
The Str::orderedUuid
method generates a "timestamp first" UUID that may be efficiently stored in an indexed database column:
use Illuminate\Support\Str;
return (string) Str::orderedUuid();
Str::plural()
The Str::plural
method converts a string to its plural form. This function currently only supports the English language:
use Illuminate\Support\Str;
$plural = Str::plural('car');
// cars
$plural = Str::plural('child');
// children
You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string:
use Illuminate\Support\Str;
$plural = Str::plural('child', 2);
// children
$plural = Str::plural('child', 1);
// child
Str::random()
The Str::random
method generates a random string of the specified length. This function uses PHP's random_bytes
function:
use Illuminate\Support\Str;
$random = Str::random(40);
Str::replaceArray()
The Str::replaceArray
method replaces a given value in the string sequentially using an array:
use Illuminate\Support\Str;
$string = 'The event will take place between ? and ?';
$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);
// The event will take place between 8:30 and 9:00
Str::replaceFirst()
The Str::replaceFirst
method replaces the first occurrence of a given value in a string:
use Illuminate\Support\Str;
$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');
// a quick brown fox jumps over the lazy dog
Str::replaceLast()
The Str::replaceLast
method replaces the last occurrence of a given value in a string:
use Illuminate\Support\Str;
$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');
// the quick brown fox jumps over a lazy dog
Str::singular()
The Str::singular
method converts a string to its singular form. This function currently only supports the English language:
use Illuminate\Support\Str;
$singular = Str::singular('cars');
// car
$singular = Str::singular('children');
// child