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

array_addarray_collapsearray_dividearray_dotarray_exceptarray_firstarray_flattenarray_forgetarray_getarray_hasarray_lastarray_onlyarray_pluckarray_prependarray_pullarray_setarray_sortarray_sort_recursivearray_wherearray_wrapheadlast

Paths

app_pathbase_pathconfig_pathdatabase_pathmixpublic_pathresource_pathstorage_path

Strings

camel_caseclass_basenameeends_withkebab_casesnake_casestr_limitstarts_withstr_afterstr_containsstr_finishstr_isstr_pluralstr_randomstr_singularstr_slugstudly_casetitle_casetranstrans_choice

URLs

actionassetsecure_assetroutesecure_urlurl

Miscellaneous

abortabort_ifabort_unlessauthbackbcryptcachecollectconfigcsrf_fieldcsrf_tokendddispatchenveventfactoryinfologgermethod_fieldoldredirectrequestresponseretrysessionvalueview

Method Listing

Arrays

array_add()

The array_add function adds a given key / value pair to the array if the given key doesn't already exist in the array:

  1. $array = array_add(['name' => 'Desk'], 'price', 100);
  2. // ['name' => 'Desk', 'price' => 100]

array_collapse()

The array_collapse function collapses an array of arrays into a single array:

  1. $array = array_collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
  2. // [1, 2, 3, 4, 5, 6, 7, 8, 9]

array_divide()

The array_divide function returns two arrays, one containing the keys, and the other containing the values of the original array:

  1. list($keys, $values) = array_divide(['name' => 'Desk']);
  2. // $keys: ['name']
  3. // $values: ['Desk']

array_dot()

The array_dot function flattens a multi-dimensional array into a single level array that uses "dot" notation to indicate depth:

  1. $array = array_dot(['foo' => ['bar' => 'baz']]);
  2. // ['foo.bar' => 'baz'];

array_except()

The array_except function removes the given key / value pairs from the array:

  1. $array = ['name' => 'Desk', 'price' => 100];
  2. $array = array_except($array, ['price']);
  3. // ['name' => 'Desk']

array_first()

The array_first function returns the first element of an array passing a given truth test:

  1. $array = [100, 200, 300];
  2. $value = array_first($array, function ($value, $key) {
  3. return $value >= 150;
  4. });
  5. // 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:

  1. $value = array_first($array, $callback, $default);

array_flatten()

The array_flatten function will flatten a multi-dimensional array into a single level.

  1. $array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
  2. $array = array_flatten($array);
  3. // ['Joe', 'PHP', 'Ruby'];

array_forget()

The array_forget function removes a given key / value pair from a deeply nested array using "dot" notation:

  1. $array = ['products' => ['desk' => ['price' => 100]]];
  2. array_forget($array, 'products.desk');
  3. // ['products' => []]

array_get()

The array_get function retrieves a value from a deeply nested array using "dot" notation:

  1. $array = ['products' => ['desk' => ['price' => 100]]];
  2. $value = array_get($array, 'products.desk');
  3. // ['price' => 100]

The array_get function also accepts a default value, which will be returned if the specific key is not found:

  1. $value = array_get($array, 'names.john', 'default');

array_has()

The array_has function checks that a given item or items exists in an array using "dot" notation:

  1. $array = ['product' => ['name' => 'desk', 'price' => 100]];
  2. $hasItem = array_has($array, 'product.name');
  3. // true
  4. $hasItems = array_has($array, ['product.price', 'product.discount']);
  5. // false

array_last()

The array_last function returns the last element of an array passing a given truth test:

  1. $array = [100, 200, 300, 110];
  2. $value = array_last($array, function ($value, $key) {
  3. return $value >= 150;
  4. });
  5. // 300

array_only()

The array_only function will return only the specified key / value pairs from the given array:

  1. $array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
  2. $array = array_only($array, ['name', 'price']);
  3. // ['name' => 'Desk', 'price' => 100]

array_pluck()

The array_pluck function will pluck a list of the given key / value pairs from the array:

  1. $array = [
  2. ['developer' => ['id' => 1, 'name' => 'Taylor']],
  3. ['developer' => ['id' => 2, 'name' => 'Abigail']],
  4. ];
  5. $array = array_pluck($array, 'developer.name');
  6. // ['Taylor', 'Abigail'];

You may also specify how you wish the resulting list to be keyed:

  1. $array = array_pluck($array, 'developer.name', 'developer.id');
  2. // [1 => 'Taylor', 2 => 'Abigail'];

array_prepend()

The array_prepend function will push an item onto the beginning of an array:

  1. $array = ['one', 'two', 'three', 'four'];
  2. $array = array_prepend($array, 'zero');
  3. // $array: ['zero', 'one', 'two', 'three', 'four']

array_pull()

The array_pull function returns and removes a key / value pair from the array:

  1. $array = ['name' => 'Desk', 'price' => 100];
  2. $name = array_pull($array, 'name');
  3. // $name: Desk
  4. // $array: ['price' => 100]

array_set()

The array_set function sets a value within a deeply nested array using "dot" notation:

  1. $array = ['products' => ['desk' => ['price' => 100]]];
  2. array_set($array, 'products.desk.price', 200);
  3. // ['products' => ['desk' => ['price' => 200]]]

array_sort()

The array_sort function sorts the array by the results of the given Closure:

  1. $array = [
  2. ['name' => 'Desk'],
  3. ['name' => 'Chair'],
  4. ];
  5. $array = array_values(array_sort($array, function ($value) {
  6. return $value['name'];
  7. }));
  8. /*
  9. [
  10. ['name' => 'Chair'],
  11. ['name' => 'Desk'],
  12. ]
  13. */

array_sort_recursive()

The array_sort_recursive function recursively sorts the array using the sort function:

  1. $array = [
  2. [
  3. 'Roman',
  4. 'Taylor',
  5. 'Li',
  6. ],
  7. [
  8. 'PHP',
  9. 'Ruby',
  10. 'JavaScript',
  11. ],
  12. ];
  13. $array = array_sort_recursive($array);
  14. /*
  15. [
  16. [
  17. 'Li',
  18. 'Roman',
  19. 'Taylor',
  20. ],
  21. [
  22. 'JavaScript',
  23. 'PHP',
  24. 'Ruby',
  25. ]
  26. ];
  27. */

array_where()

The array_where function filters the array using the given Closure:

  1. $array = [100, '200', 300, '400', 500];
  2. $array = array_where($array, function ($value, $key) {
  3. return is_string($value);
  4. });
  5. // [1 => 200, 3 => 400]

array_wrap()

The array_wrap function will wrap the given value in an array. If the given value is already an array it will not be changed:

  1. $string = 'Laravel';
  2. $array = array_wrap($string);
  3. // [0 => 'Laravel']

head()

The head function returns the first element in the given array:

  1. $array = [100, 200, 300];
  2. $first = head($array);
  3. // 100

last()

The last function returns the last element in the given array:

  1. $array = [100, 200, 300];
  2. $last = last($array);
  3. // 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:

  1. $path = app_path();
  2. $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:

  1. $path = base_path();
  2. $path = base_path('vendor/bin');

config_path()

The config_path function returns the fully qualified path to the application configuration directory:

  1. $path = config_path();

database_path()

The database_path function returns the fully qualified path to the application's database directory:

  1. $path = database_path();

mix()

The mix function gets the path to a versioned Mix file:

  1. mix($file);

public_path()

The public_path function returns the fully qualified path to the public directory:

  1. $path = public_path();

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 relative to the resources directory:

  1. $path = resource_path();
  2. $path = resource_path('assets/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 relative to the storage directory:

  1. $path = storage_path();
  2. $path = storage_path('app/file.txt');

Strings

camel_case()

The camel_case function converts the given string to camelCase:

  1. $camel = camel_case('foo_bar');
  2. // fooBar

class_basename()

The class_basename returns the class name of the given class with the class' namespace removed:

  1. $class = class_basename('Foo\Bar\Baz');
  2. // Baz

e()

The e function runs PHP's htmlspecialchars function with the double_encode option set to false:

  1. echo e('<html>foo</html>');
  2. // &lt;html&gt;foo&lt;/html&gt;

ends_with()

The ends_with function determines if the given string ends with the given value:

  1. $value = ends_with('This is my name', 'name');
  2. // true

kebab_case()

The kebab_case function converts the given string to kebab-case:

  1. $value = kebab_case('fooBar');
  2. // foo-bar

snake_case()

The snake_case function converts the given string to snake_case:

  1. $snake = snake_case('fooBar');
  2. // foo_bar

str_limit()

The str_limit function limits the number of characters in a string. The function accepts a string as its first argument and the maximum number of resulting characters as its second argument:

  1. $value = str_limit('The PHP framework for web artisans.', 7);
  2. // The PHP...

starts_with()

The starts_with function determines if the given string begins with the given value:

  1. $value = starts_with('This is my name', 'This');
  2. // true

str_after()

The str_after function returns everything after the given value in a string:

  1. $value = str_after('This is: a test', 'This is:');
  2. // ' a test'

str_contains()

The str_contains function determines if the given string contains the given value:

  1. $value = str_contains('This is my name', 'my');
  2. // true

You may also pass an array of values to determine if the given string contains any of the values:

  1. $value = str_contains('This is my name', ['my', 'foo']);
  2. // true

str_finish()

The str_finish function adds a single instance of the given value to a string if it does not already end with it:

  1. $string = str_finish('this/string', '/');
  2. $string2 = str_finish('this/string/', '/');
  3. // this/string/

str_is()

The str_is function determines if a given string matches a given pattern. Asterisks may be used to indicate wildcards:

  1. $value = str_is('foo*', 'foobar');
  2. // true
  3. $value = str_is('baz*', 'foobar');
  4. // false

str_plural()

The str_plural function converts a string to its plural form. This function currently only supports the English language:

  1. $plural = str_plural('car');
  2. // cars
  3. $plural = str_plural('child');
  4. // children

You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string:

  1. $plural = str_plural('child', 2);
  2. // children
  3. $plural = str_plural('child', 1);
  4. // child

str_random()

The str_random function generates a random string of the specified length. This function uses PHP's random_bytes function:

  1. $string = str_random(40);

str_singular()

The str_singular function converts a string to its singular form. This function currently only supports the English language:

  1. $singular = str_singular('cars');
  2. // car

str_slug()

The str_slug function generates a URL friendly "slug" from the given string:

  1. $title = str_slug('Laravel 5 Framework', '-');
  2. // laravel-5-framework

studly_case()

The studly_case function converts the given string to StudlyCase:

  1. $value = studly_case('foo_bar');
  2. // FooBar

title_case()

The title_case function converts the given string to Title Case:

  1. $title = title_case('a nice title uses the correct case');
  2. // A Nice Title Uses The Correct Case

trans()

The trans function translates the given language line using your localization files:

  1. echo trans('validation.required'):

trans_choice()

The trans_choice function translates the given language line with inflection:

  1. $value = trans_choice('foo.bar', $count);

URLs

action()

The action function generates a URL for the given controller action. You do not need to pass the full namespace to the controller. Instead, pass the controller class name relative to the App\Http\Controllers namespace:

  1. $url = action('[email protected]');

If the method accepts route parameters, you may pass them as the second argument to the method:

  1. $url = action('[email protected]', ['id' => 1]);

asset()

Generate a URL for an asset using the current scheme of the request (HTTP or HTTPS):

  1. $url = asset('img/photo.jpg');

secure_asset()

Generate a URL for an asset using HTTPS:

  1. echo secure_asset('foo/bar.zip');

route()

The route function generates a URL for the given named route:

  1. $url = route('routeName');

If the route accepts parameters, you may pass them as the second argument to the method:

  1. $url = route('routeName', ['id' => 1]);

By default, the route function generates an absolute URL. If you wish to generate a relative URL, you may pass false as the third parameter:

  1. $url = route('routeName', ['id' => 1], false);

secure_url()

The secure_url function generates a fully qualified HTTPS URL to the given path:

  1. echo secure_url('user/profile');
  2. echo secure_url('user/profile', [1]);

url()

The url function generates a fully qualified URL to the given path:

  1. echo url('user/profile');
  2. echo url('user/profile', [1]);

If no path is provided, a Illuminate\Routing\UrlGenerator instance is returned:

  1. echo url()->current();
  2. echo url()->full();
  3. echo url()->previous();

Miscellaneous

abort()

The abort function throws a HTTP exception which will be rendered by the exception handler:

  1. abort(401);

You may also provide the exception's response text:

  1. abort(401, 'Unauthorized.');

abort_if()

The abort_if function throws an HTTP exception if a given boolean expression evaluates to true:

  1. abort_if(! Auth::user()->isAdmin(), 403);

abort_unless()

The abort_unless function throws an HTTP exception if a given boolean expression evaluates to false:

  1. abort_unless(Auth::user()->isAdmin(), 403);

auth()

The auth function returns an authenticator instance. You may use it instead of the Auth facade for convenience:

  1. $user = auth()->user();

back()

The back() function generates a redirect response to the user's previous location:

  1. return back();

bcrypt()

The bcrypt function hashes the given value using Bcrypt. You may use it as an alternative to the Hash facade:

  1. $password = bcrypt('my-secret-password');

cache()

The cache function may be used to get values from the cache. If the given key does not exist in the cache, an optional default value will be returned:

  1. $value = cache('key');
  2. $value = cache('key', 'default');

You may add items to the cache by passing an array of key / value pairs to the function. You should also pass the number of minutes or duration the cached value should be considered valid:

  1. cache(['key' => 'value'], 5);
  2. cache(['key' => 'value'], Carbon::now()->addSeconds(10));

collect()

The collect function creates a collection instance from the given array:

  1. $collection = collect(['taylor', 'abigail']);

config()

The config function gets the value of a configuration variable. The configuration values may be accessed using "dot" syntax, which includes the name of the file and the option you wish to access. A default value may be specified and is returned if the configuration option does not exist:

  1. $value = config('app.timezone');
  2. $value = config('app.timezone', $default);

The config helper may also be used to set configuration variables at runtime by passing an array of key / value pairs:

  1. config(['app.debug' => true]);

csrf_field()

The csrf_field function generates an HTML hidden input field containing the value of the CSRF token. For example, using Blade syntax:

  1. {{ csrf_field() }}

csrf_token()

The csrf_token function retrieves the value of the current CSRF token:

  1. $token = csrf_token();

dd()

The dd function dumps the given variables and ends execution of the script:

  1. dd($value);
  2. dd($value1, $value2, $value3, ...);

If you do not want to halt the execution of your script, use the dump function instead:

  1. dump($value);

dispatch()

The dispatch function pushes a new job onto the Laravel job queue:

  1. dispatch(new App\Jobs\SendEmails);

env()

The env function gets the value of an environment variable or returns a default value:

  1. $env = env('APP_ENV');
  2. // Return a default value if the variable doesn't exist...
  3. $env = env('APP_ENV', 'production');

event()

The event function dispatches the given event to its listeners:

  1. event(new UserRegistered($user));

factory()

The factory function creates a model factory builder for a given class, name, and amount. It can be used while testing or seeding:

  1. $user = factory(App\User::class)->make();

info()

The info function will write information to the log:

  1. info('Some helpful information!');

An array of contextual data may also be passed to the function:

  1. info('User login attempt failed.', ['id' => $user->id]);

logger()

The logger function can be used to write a debug level message to the log:

  1. logger('Debug message');

An array of contextual data may also be passed to the function:

  1. logger('User has logged in.', ['id' => $user->id]);

A logger instance will be returned if no value is passed to the function:

  1. logger()->error('You are not allowed here.');

method_field()

The method_field function generates an HTML hidden input field containing the spoofed value of the form's HTTP verb. For example, using Blade syntax:

  1. <form method="POST">
  2. {{ method_field('DELETE') }}
  3. </form>

old()

The old function retrieves an old input value flashed into the session:

  1. $value = old('value');
  2. $value = old('value', 'default');

redirect()

The redirect function returns a redirect HTTP response, or returns the redirector instance if called with no arguments:

  1. return redirect('/home');
  2. return redirect()->route('route.name');

request()

The request function returns the current request instance or obtains an input item:

  1. $request = request();
  2. $value = request('key', $default = null)

response()

The response function creates a response instance or obtains an instance of the response factory:

  1. return response('Hello World', 200, $headers);
  2. return response()->json(['foo' => 'bar'], 200, $headers);

retry()

The retry function attempts to execute the given callback until the given maximum attempt threshold is met. If the callback does not throw an exception, it's return value will be returned. If the callback throws an exception, it will automatically be retried. If the maximum attempt count is exceeded, the exception will be thrown:

  1. return retry(5, function () {
  2. // Attempt 5 times while resting 100ms in between attempts...
  3. }, 100);

session()

The session function may be used to get or set session values:

  1. $value = session('key');

You may set values by passing an array of key / value pairs to the function:

  1. session(['chairs' => 7, 'instruments' => 3]);

The session store will be returned if no value is passed to the function:

  1. $value = session()->get('key');
  2. session()->put('key', $value);

value()

The value function's behavior will simply return the value it is given. However, if you pass a Closure to the function, the Closure will be executed then its result will be returned:

  1. $value = value(function () {
  2. return 'bar';
  3. });

view()

The view function retrieves a view instance:

  1. return view('auth.login');