Помощники
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::dotArr::exceptArr::existsArr::firstArr::flattenArr::forgetArr::getArr::hasArr::hasAnyArr::isAssocArr::lastArr::onlyArr::pluckArr::prependArr::pullArr::queryArr::randomArr::setArr::shuffleArr::sortArr::sortRecursiveArr::whereArr::wrapdata_filldata_getdata_setheadlast
Paths
[app\_path](#method-app-path) [base\_path](#method-base-path) [config\_path](#method-config-path) [database\_path](#method-database-path) [mix](#method-mix) [public\_path](#method-public-path) [resource\_path](#method-resource-path) [storage\_path](#method-storage-path)
Strings
__class_basenameepreg_replace_arrayStr::afterStr::afterLastStr::asciiStr::beforeStr::beforeLastStr::betweenStr::camelStr::containsStr::containsAllStr::endsWithStr::finishStr::isStr::isAsciiStr::isUuidStr::kebabStr::lengthStr::limitStr::lowerStr::orderedUuidStr::pluralStr::randomStr::replaceArrayStr::replaceFirstStr::replaceLastStr::singularStr::slugStr::snakeStr::startStr::startsWithStr::studlyStr::substrStr::titleStr::ucfirstStr::upperStr::uuidStr::wordstranstrans_choice
Fluent Strings
afterafterLastappendasciibasenamebeforebeforeLastcamelcontainscontainsAlldirnameendsWithexactlyexplodefinishisisAsciiisEmptyisNotEmptykebablengthlimitlowerltrimmatchmatchAllpluralprependreplacereplaceArrayreplaceFirstreplaceLastreplaceMatchesrtrimsingularslugsnakesplitstartstartsWithstudlysubstrtitletrimucfirstupperwhenwhenEmptywords
URLs
actionassetroutesecure_assetsecure_urlurl
Miscellaneous
abortabort_ifabort_unlessappauthbackbcryptblankbroadcastcacheclass_uses_recursivecollectconfigcookiecsrf_fieldcsrf_tokendddispatchdispatch_nowdumpenveventfactoryfilledinfologgermethod_fieldnowoldoptionalpolicyredirectreportrequestrescueresolveresponseretrysessiontapthrow_ifthrow_unlesstodaytrait_uses_recursivetransformvalidatorvalueviewwith
Method Listing
Arrays & Objects
Arr::accessible()
The Arr::accessible
method checks that the given value is array accessible:
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
:
Arr::collapse()
The Arr::collapse
method collapses an array of arrays into a single array:
Arr::crossJoin()
The Arr::crossJoin
method cross joins the given arrays, returning a Cartesian product with all possible permutations:
Arr::divide()
The Arr::divide
method returns two arrays, one containing the keys, and the other containing the values of the given array:
Arr::dot()
The Arr::dot
method flattens a multi-dimensional array into a single level array that uses "dot" notation to indicate depth:
Arr::except()
The Arr::except
method removes the given key / value pairs from an array:
Arr::exists()
The Arr::exists
method checks that the given key exists in the provided array:
Arr::first()
The Arr::first
method returns the first element of an array passing a given truth test:
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:
Arr::flatten()
The Arr::flatten
method flattens a multi-dimensional array into a single level array:
Arr::forget()
The Arr::forget
method removes a given key / value pair from a deeply nested array using "dot" notation:
Arr::get()
The Arr::get
method retrieves a value from a deeply nested array using "dot" notation:
The Arr::get
method also accepts a default value, which will be returned if the specific key is not found:
Arr::has()
The Arr::has
method checks whether a given item or items exists in an array using "dot" notation:
Arr::hasAny()
The Arr::hasAny
method checks whether any item in a given set exists in an array using "dot" notation:
Arr::isAssoc()
The Arr::isAssoc
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:
Arr::last()
The Arr::last
method returns the last element of an array passing a given truth test:
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:
Arr::only()
The Arr::only
method returns only the specified key / value pairs from the given array:
Arr::pluck()
The Arr::pluck
method retrieves all of the values for a given key from an array:
You may also specify how you wish the resulting list to be keyed:
Arr::prepend()
The Arr::prepend
method will push an item onto the beginning of an array:
If needed, you may specify the key that should be used for the value:
Arr::pull()
The Arr::pull
method returns and removes a key / value pair from an array:
A default value may be passed as the third argument to the method. This value will be returned if the key doesn't exist:
Arr::query()
The Arr::query
method converts the array into a query string:
Arr::random()
The Arr::random
method returns a random value from an array:
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:
Arr::set()
The Arr::set
method sets a value within a deeply nested array using "dot" notation:
Arr::shuffle()
The Arr::shuffle
method randomly shuffles the items in the array:
Arr::sort()
The Arr::sort
method sorts an array by its values:
You may also sort the array by the results of the given Closure:
Arr::sortRecursive()
The Arr::sortRecursive
method recursively sorts an array using the sort
function for numeric sub=arrays and ksort
for associative subarrays:
Arr::where()
The Arr::where
method filters an array using the given Closure:
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:
If the given value is null, an empty array will be returned:
data_fill()
The data_fill
function sets a missing value within a nested array or object using "dot" notation:
This function also accepts asterisks as wildcards and will fill the target accordingly:
data_get()
The data_get
function retrieves a value from a nested array or object using "dot" notation:
The data_get
function also accepts a default value, which will be returned if the specified key is not found:
The function also accepts wildcards using asterisks, which may target any key of the array or object:
data_set()
The data_set
function sets a value within a nested array or object using "dot" notation:
This function also accepts wildcards and will set values on the target accordingly:
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:
head()
The head
function returns the first element in the given array:
last()
The last
function returns the last element in the given array:
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:
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:
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:
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:
mix()
The mix
function returns the path to a versioned Mix file:
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:
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:
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:
__()
The __
function translates the given translation string or translation key using your localization files:
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's namespace removed:
e()
The e
function runs PHP's htmlspecialchars
function with the double_encode
option set to true
by default:
preg_replace_array()
The preg_replace_array
function replaces a given pattern in the string sequentially using an array:
Str::after()
The Str::after
method returns everything after the given value in a string. The entire string will be returned if the value does not exist within the string:
Str::afterLast()
The Str::afterLast
method returns everything after the last occurrence of the given value in a string. The entire string will be returned if the value does not exist within the string:
Str::ascii()
The Str::ascii
method will attempt to transliterate the string into an ASCII value:
Str::before()
The Str::before
method returns everything before the given value in a string:
Str::beforeLast()
The Str::beforeLast
method returns everything before the last occurrence of the given value in a string:
Str::between()
The Str::between
method returns the portion of a string between two values:
Str::camel()
The Str::camel
method converts the given string to camelCase
:
Str::contains()
The Str::contains
method determines if the given string contains the given value (case sensitive):
You may also pass an array of values to determine if the given string contains any of the values:
Str::containsAll()
The Str::containsAll
method determines if the given string contains all array values:
Str::endsWith()
The Str::endsWith
method determines if the given string ends with the given value:
You may also pass an array of values to determine if the given string ends with any of the given values:
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:
Str::is()
The Str::is
method determines if a given string matches a given pattern. Asterisks may be used to indicate wildcards:
Str::isAscii()
The Str::isAscii
method determines if a given string is 7 bit ASCII:
Str::isUuid()
The Str::isUuid
method determines if the given string is a valid UUID:
Str::kebab()
The Str::kebab
method converts the given string to kebab-case
:
Str::length()
The Str::length
method returns the length of the given string:
Str::limit()
The Str::limit
method truncates the given string at the specified length:
You may also pass a third argument to change the string that will be appended to the end:
Str::lower()
The Str::lower
method converts the given string to lowercase:
Str::orderedUuid()
The Str::orderedUuid
method generates a "timestamp first" UUID that may be efficiently stored in an indexed database column:
Str::plural()
The Str::plural
method converts a single word string to its plural form. This function currently only supports the English language:
You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string:
Str::random()
The Str::random
method generates a random string of the specified length. This function uses PHP's random_bytes
function:
Str::replaceArray()
The Str::replaceArray
method replaces a given value in the string sequentially using an array:
Str::replaceFirst()
The Str::replaceFirst
method replaces the first occurrence of a given value in a string:
Str::replaceLast()
The Str::replaceLast
method replaces the last occurrence of a given value in a string:
Str::singular()
The Str::singular
method converts a string to its singular form. This function currently only supports the English language:
Str::slug()
The Str::slug
method generates a URL friendly "slug" from the given string:
Str::snake()
The Str::snake
method converts the given string to snake_case
:
Str::start()
The Str::start
method adds a single instance of the given value to a string if it does not already start with the value:
Str::startsWith()
The Str::startsWith
method determines if the given string begins with the given value:
Str::studly()
The Str::studly
method converts the given string to StudlyCase
:
Str::substr()
The Str::substr
method returns the portion of string specified by the start and length parameters:
Str::title()
The Str::title
method converts the given string to Title Case
:
Str::ucfirst()
The Str::ucfirst
method returns the given string with the first character capitalized:
Str::upper()
The Str::upper
method converts the given string to uppercase:
Str::uuid()
The Str::uuid
method generates a UUID (version 4):
Str::words()
The Str::words
method limits the number of words in a string:
trans()
The trans
function translates the given translation key using your localization files:
If the specified translation key does not exist, the trans
function will return the given key. So, using the example above, the trans
function would return messages.welcome
if the translation key does not exist.
trans_choice()
The trans_choice
function translates the given translation key with inflection:
If the specified translation key does not exist, the trans_choice
function will return the given key. So, using the example above, the trans_choice
function would return messages.notifications
if the translation key does not exist.
Fluent strings provide a more fluent, object-oriented interface for working with string values, allowing you to chain multiple string operations together using a more readable syntax compared to traditional string operations.
after
The after
method returns everything after the given value in a string. The entire string will be returned if the value does not exist within the string:
afterLast
The afterLast
method returns everything after the last occurrence of the given value in a string. The entire string will be returned if the value does not exist within the string:
append
The append
method appends the given values to the string:
ascii
The ascii
method will attempt to transliterate the string into an ASCII value:
basename
The basename
method will return the trailing name component of the given string:
If needed, you may provide an "extension" that will be removed from the trailing component:
before
The before
method returns everything before the given value in a string:
beforeLast
The beforeLast
method returns everything before the last occurrence of the given value in a string:
camel
The camel
method converts the given string to camelCase
:
contains
The contains
method determines if the given string contains the given value (case sensitive):
You may also pass an array of values to determine if the given string contains any of the values:
containsAll
The containsAll
method determines if the given string contains all array values:
dirname
The dirname
method returns the parent directory portion of the given string:
Optionally, You may specify how many directory levels you wish to trim from the string:
endsWith
The endsWith
method determines if the given string ends with the given value:
You may also pass an array of values to determine if the given string ends with any of the given values:
exactly
The exactly
method determines if the given string is an exact match with another string:
explode
The explode
method splits the string by the given delimiter and returns a collection containing each section of the split string:
finish
The finish
method adds a single instance of the given value to a string if it does not already end with the value:
is
The is
method determines if a given string matches a given pattern. Asterisks may be used to indicate wildcards:
isAscii
The isAscii
method determines if a given string is an ASCII string:
isEmpty
The isEmpty
method determines if the given string is empty:
isNotEmpty
The isNotEmpty
method determines if the given string is not empty:
kebab
The kebab
method converts the given string to kebab-case
:
length
The length
method returns the length of the given string:
limit
The limit
method truncates the given string at the specified length:
You may also pass a third argument to change the string that will be appended to the end:
lower
The lower
method converts the given string to lowercase:
ltrim
The ltrim
method left trims the given string:
match
The match
method will return the portion of a string that matches a given regular expression pattern:
matchAll
The matchAll
method will return a collection containing the portions of a string that match a given regular expression pattern:
If you specify a matching group within the expression, Laravel will return a collection of that group's matches:
If no matches are found, an empty collection will be returned.
plural
The plural
method converts a single word string to its plural form. This function currently only supports the English language:
You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string:
prepend
The prepend
method prepends the given values onto the string:
replace
The replace
method replaces a given string within the string:
replaceArray
The replaceArray
method replaces a given value in the string sequentially using an array:
replaceFirst
The replaceFirst
method replaces the first occurrence of a given value in a string:
replaceLast
The replaceLast
method replaces the last occurrence of a given value in a string:
replaceMatches
The replaceMatches
method replaces all portions of a string matching a given pattern with the given replacement string:
The replaceMatches
method also accepts a Closure that will be invoked with each portion of the string matching the given party, allowing you to perform the replacement logic within the Closure and return the replaced value:
rtrim
The rtrim
method right trims the given string:
singular
The singular
method converts a string to its singular form. This function currently only supports the English language:
slug
The slug
method generates a URL friendly "slug" from the given string:
snake
The snake
method converts the given string to snake_case
:
split
The split
method splits a string into a collection using a regular expression:
start
The start
method adds a single instance of the given value to a string if it does not already start with the value:
startsWith
The startsWith
method determines if the given string begins with the given value:
studly
The studly
method converts the given string to StudlyCase
:
substr
The substr
method returns the portion of the string specified by the given start and length parameters:
title
The title
method converts the given string to Title Case
:
trim
The trim
method trims the given string:
ucfirst
The ucfirst
method returns the given string with the first character capitalized:
upper
The upper
method converts the given string to uppercase:
when
The when
method invokes the given Closure if a given condition is true. The Closure will receive the fluent string instance:
If necessary, you may pass another Closure as the third parameter to the when
method. This Closure will execute if the condition parameter evaluates to false
.
whenEmpty
The whenEmpty
method invokes the given Closure if the string is empty. If the Closure returns a value, that value will also be returned by the whenEmpty
method. If the Closure does not return a value, the fluent string instance will be returned:
words
The words
method limits the number of words in a string:
action()
The action
function generates a URL for the given controller action. You do not need to pass the full namespace of the controller. Instead, pass the controller class name relative to the App\Http\Controllers
namespace:
If the method accepts route parameters, you may pass them as the second argument to the method:
asset()
The asset
function generates a URL for an asset using the current scheme of the request (HTTP or HTTPS):
You can configure the asset URL host by setting the ASSET_URL
variable in your .env
file. This can be useful if you host your assets on an external service like Amazon S3:
route()
The route
function generates a URL for the given named route:
If the route accepts parameters, you may pass them as the second argument to the method:
By default, the route
function generates an absolute URL. If you wish to generate a relative URL, you may pass false
as the third argument:
secure_asset()
The secure_asset
function generates a URL for an asset using HTTPS:
secure_url()
The secure_url
function generates a fully qualified HTTPS URL to the given path:
url()
The url
function generates a fully qualified URL to the given path:
If no path is provided, a Illuminate\Routing\UrlGenerator
instance is returned:
abort()
The abort
function throws an HTTP exception which will be rendered by the exception handler:
You may also provide the exception's response text and custom response headers:
abort_if()
The abort_if
function throws an HTTP exception if a given boolean expression evaluates to true
:
Like the abort
method, you may also provide the exception's response text as the third argument and an array of custom response headers as the fourth argument.
abort_unless()
The abort_unless
function throws an HTTP exception if a given boolean expression evaluates to false
:
Like the abort
method, you may also provide the exception's response text as the third argument and an array of custom response headers as the fourth argument.
app()
The app
function returns the service container instance:
You may pass a class or interface name to resolve it from the container:
auth()
The auth
function returns an authenticator instance. You may use it instead of the Auth
facade for convenience:
If needed, you may specify which guard instance you would like to access:
back()
The back
function generates a redirect HTTP response to the user's previous location:
bcrypt()
The bcrypt
function hashes the given value using Bcrypt. You may use it as an alternative to the Hash
facade:
blank()
The blank
function returns whether the given value is "blank":
For the inverse of blank
, see the filled
method.
broadcast()
The broadcast
function broadcasts the given event to its listeners:
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:
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 seconds or duration the cached value should be considered valid:
class_uses_recursive()
The class_uses_recursive
function returns all traits used by a class, including traits used by all of its parent classes:
collect()
The collect
function creates a collection instance from the given value:
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:
You may set configuration variables at runtime by passing an array of key / value pairs:
cookie()
The cookie
function creates a new cookie instance:
csrf_field()
The csrf_field
function generates an HTML hidden
input field containing the value of the CSRF token. For example, using Blade syntax:
csrf_token()
The csrf_token
function retrieves the value of the current CSRF token:
dd()
The dd
function dumps the given variables and ends execution of the script:
If you do not want to halt the execution of your script, use the dump
function instead.
dispatch()
The dispatch
function pushes the given job onto the Laravel job queue:
dispatch_now()
The dispatch_now
function runs the given job immediately and returns the value from its handle
method:
dump()
The dump
function dumps the given variables:
If you want to stop executing the script after dumping the variables, use the dd
function instead.
env()
The env
function retrieves the value of an environment variable or returns a default value:
If you execute the
config:cache
command during your deployment process, you should be sure that you are only calling theenv
function from within your configuration files. Once the configuration has been cached, the.env
file will not be loaded and all calls to theenv
function will returnnull
.
event()
The event
function dispatches the given event to its listeners:
factory()
The factory
function creates a model factory builder for a given class, name, and amount. It can be used while testing or seeding:
filled()
The filled
function returns whether the given value is not "blank":
For the inverse of filled
, see the blank
method.
info()
The info
function will write information to the log:
An array of contextual data may also be passed to the function:
logger()
The logger
function can be used to write a debug
level message to the log:
An array of contextual data may also be passed to the function:
A logger instance will be returned if no value is passed to the function:
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:
now()
The now
function creates a new Illuminate\Support\Carbon
instance for the current time:
old()
The old
function retrieves an old input value flashed into the session:
optional()
The optional
function accepts any argument and allows you to access properties or call methods on that object. If the given object is null
, properties and methods will return null
instead of causing an error:
The optional
function also accepts a Closure as its second argument. The Closure will be invoked if the value provided as the first argument is not null:
policy()
The policy
method retrieves a policy instance for a given class:
redirect()
The redirect
function returns a redirect HTTP response, or returns the redirector instance if called with no arguments:
report()
The report
function will report an exception using your exception handler's report
method:
request()
The request
function returns the current request instance or obtains an input item:
rescue()
The rescue
function executes the given Closure and catches any exceptions that occur during its execution. All exceptions that are caught will be sent to your exception handler's report
method; however, the request will continue processing:
You may also pass a second argument to the rescue
function. This argument will be the "default" value that should be returned if an exception occurs while executing the Closure:
resolve()
The resolve
function resolves a given class or interface name to its instance using the service container:
response()
The response
function creates a response instance or obtains an instance of the response factory:
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, its 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:
session()
The session
function may be used to get or set session values:
You may set values by passing an array of key / value pairs to the function:
The session store will be returned if no value is passed to the function:
tap()
The tap
function accepts two arguments: an arbitrary $value
and a Closure. The $value
will be passed to the Closure and then be returned by the tap
function. The return value of the Closure is irrelevant:
If no Closure is passed to the tap
function, you may call any method on the given $value
. The return value of the method you call will always be $value
, regardless of what the method actually returns in its definition. For example, the Eloquent update
method typically returns an integer. However, we can force the method to return the model itself by chaining the update
method call through the tap
function:
To add a tap
method to a class, you may add the Illuminate\Support\Traits\Tappable
trait to the class. The tap
method of this trait accepts a Closure as its only argument. The object instance itself will be passed to the Closure and then be returned by the tap
method:
throw_if()
The throw_if
function throws the given exception if a given boolean expression evaluates to true
:
throw_unless()
The throw_unless
function throws the given exception if a given boolean expression evaluates to false
:
today()
The today
function creates a new Illuminate\Support\Carbon
instance for the current date:
trait_uses_recursive()
The trait_uses_recursive
function returns all traits used by a trait:
transform()
The transform
function executes a Closure
on a given value if the value is not blank and returns the result of the Closure
:
A default value or Closure
may also be passed as the third parameter to the method. This value will be returned if the given value is blank:
validator()
The validator
function creates a new validator instance with the given arguments. You may use it instead of the Validator
facade for convenience:
value()
The value
function returns 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:
view()
The view
function retrieves a view instance:
with()
The with
function returns the value it is given. If a Closure
is passed as the second argument to the function, the Closure
will be executed and its result will be returned:
Last updated