How To Clean A String Of Characters So It Can Be Used In The Url Php
Helpers
- Introduction
- Available Methods
Introduction
Laravel includes a variety of global "helper" PHP functions. Many of these functions are used by the framework itself; however, you are gratis to employ them in your ain applications if you find them convenient.
Available Methods
Arrays & Objects
Paths
Strings
Fluent Strings
URLs
Miscellaneous
Method List
Arrays & Objects
Arr::accessible()
The Arr::accessible
method determines if the given value is array attainable:
apply Illuminate\Support\ Arr ;
use Illuminate\Support\ Collection ;
$isAccessible = Arr :: accessible ([ ' a ' => ane , ' b ' => 2 ]);
// truthful
$isAccessible = Arr :: accessible ( new Collection );
// truthful
$isAccessible = Arr :: accessible ( ' abc ' );
// fake
$isAccessible = Arr :: accessible ( new stdClass );
// false
Arr::add()
The Arr::add together
method adds a given primal / value pair to an array if the given key doesn't already exist in the array or is fix to null
:
use Illuminate\Support\ Arr ;
$array = Arr :: add ([ ' name ' => ' Desk ' ], ' price ' , 100 );
// ['name' => 'Desk', 'toll' => 100]
$array = Arr :: add ([ ' name ' => ' Desk ' , ' price ' => null ], ' cost ' , 100 );
// ['name' => 'Desk', 'cost' => 100]
Arr::collapse()
The Arr::plummet
method collapses an array of arrays into a unmarried array:
employ Illuminate\Support\ Arr ;
$array = Arr :: collapse ([[ i , 2 , 3 ], [ 4 , 5 , half dozen ], [ seven , 8 , ix ]]);
// [1, two, iii, 4, v, half dozen, 7, 8, ix]
Arr::crossJoin()
The Arr::crossJoin
method cross joins the given arrays, returning a Cartesian production with all possible permutations:
utilize Illuminate\Support\ Arr ;
$matrix = Arr :: crossJoin ([ 1 , 2 ], [ ' a ' , ' b ' ]);
/*
[
[1, 'a'],
[i, 'b'],
[two, 'a'],
[two, 'b'],
]
*/
$matrix = Arr :: crossJoin ([ i , 2 ], [ ' a ' , ' b ' ], [ ' I ' , ' 2 ' ]);
/*
[
[1, 'a', 'I'],
[ane, 'a', 'Ii'],
[1, 'b', 'I'],
[1, 'b', 'Two'],
[2, 'a', 'I'],
[2, 'a', 'Two'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
*/
Arr::divide()
The Arr::divide
method returns two arrays: i containing the keys and the other containing the values of the given array:
use Illuminate\Support\ Arr ;
[ $keys , $values ] = Arr :: dissever ([ ' name ' => ' Desk ' ]);
// $keys: ['name']
// $values: ['Desk-bound']
Arr::dot()
The Arr::dot
method flattens a multi-dimensional array into a single level array that uses "dot" notation to point depth:
utilize Illuminate\Support\ Arr ;
$array = [ ' products ' => [ ' desk ' => [ ' price ' => 100 ]]];
$flattened = Arr :: dot ( $assortment );
// ['products.desk.price' => 100]
Arr::except()
The Arr::except
method removes the given primal / value pairs from an array:
utilise Illuminate\Back up\ Arr ;
$array = [ ' proper name ' => ' Desk ' , ' price ' => 100 ];
$filtered = Arr :: except ( $array , [ ' cost ' ]);
// ['proper noun' => 'Desk']
Arr::exists()
The Arr::exists
method checks that the given key exists in the provided array:
employ Illuminate\Support\ Arr ;
$array = [ ' name ' => ' John Doe ' , ' historic period ' => 17 ];
$exists = Arr :: exists ( $array , ' proper name ' );
// true
$exists = Arr :: exists ( $array , ' salary ' );
// false
Arr::get-go()
The Arr::kickoff
method returns the first element of an array passing a given truth test:
use Illuminate\Back up\ Arr ;
$array = [ 100 , 200 , 300 ];
$commencement = Arr :: first ( $array , part ( $value , $key ) {
return $value >= 150 ;
});
// 200
A default value may too be passed as the third parameter to the method. This value volition exist returned if no value passes the truth test:
apply 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:
employ Illuminate\Support\ Arr ;
$assortment = [ ' name ' => ' Joe ' , ' languages ' => [ ' PHP ' , ' Red ' ]];
$flattened = Arr :: flatten ( $assortment );
// ['Joe', 'PHP', 'Ruby']
Arr::forget()
The Arr::forget
method removes a given fundamental / value pair from a securely nested array using "dot" notation:
apply Illuminate\Support\ Arr ;
$assortment = [ ' products ' => [ ' desk-bound ' => [ ' toll ' => 100 ]]];
Arr :: forget ( $array , ' products.desk-bound ' );
// ['products' => []]
Arr::become()
The Arr::get
method retrieves a value from a deeply nested assortment using "dot" notation:
use Illuminate\Support\ Arr ;
$assortment = [ ' products ' => [ ' desk ' => [ ' price ' => 100 ]]];
$cost = Arr :: get ( $array , ' products.desk.price ' );
// 100
The Arr::get
method too accepts a default value, which volition be returned if the specified key is not present in the array:
use Illuminate\Support\ Arr ;
$discount = Arr :: get ( $array , ' products.desk-bound.discount ' , 0 );
// 0
Arr::has()
The Arr::has
method checks whether a given particular or items exists in an array using "dot" notation:
use Illuminate\Support\ Arr ;
$array = [ ' product ' => [ ' proper name ' => ' Desk ' , ' price ' => 100 ]];
$contains = Arr :: has ( $array , ' product.name ' );
// truthful
$contains = Arr :: has ( $array , [ ' product.price ' , ' production.discount ' ]);
// false
Arr::hasAny()
The Arr::hasAny
method checks whether any detail in a given set exists in an array using "dot" notation:
employ Illuminate\Back up\ Arr ;
$array = [ ' product ' => [ ' name ' => ' Desk ' , ' price ' => 100 ]];
$contains = Arr :: hasAny ( $assortment , ' product.proper noun ' );
// true
$contains = Arr :: hasAny ( $array , [ ' product.proper noun ' , ' product.disbelieve ' ]);
// true
$contains = Arr :: hasAny ( $array , [ ' category ' , ' product.discount ' ]);
// false
Arr::isAssoc()
The Arr::isAssoc
method returns true
if the given array is an associative assortment. An array is considered "associative" if it doesn't have sequential numerical keys get-go with cipher:
apply Illuminate\Support\ Arr ;
$isAssoc = Arr :: isAssoc ([ ' product ' => [ ' proper noun ' => ' Desk ' , ' price ' => 100 ]]);
// true
$isAssoc = Arr :: isAssoc ([ 1 , 2 , three ]);
// false
Arr::isList()
The Arr::isList
method returns true
if the given array's keys are sequential integers first from zero:
use Illuminate\Support\ Arr ;
$isAssoc = Arr :: isList ([ ' foo ' , ' bar ' , ' baz ' ]);
// true
$isAssoc = Arr :: isList ([ ' production ' => [ ' proper name ' => ' Desk-bound ' , ' toll ' => 100 ]]);
// false
Arr::keyBy()
The Arr::keyBy
method keys the array by the given cardinal. If multiple items have the same key, only the terminal ane will appear in the new assortment:
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::concluding
method returns the last element of an array passing a given truth exam:
utilize Illuminate\Support\ Arr ;
$array = [ 100 , 200 , 300 , 110 ];
$final = Arr :: last ( $array , function ( $value , $key ) {
render $value >= 150 ;
});
// 300
A default value may exist passed as the third argument to the method. This value will exist returned if no value passes the truth exam:
use Illuminate\Support\ Arr ;
$concluding = Arr :: last ( $array , $callback , $default );
Arr::only()
The Arr::only
method returns merely 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 ' => i , ' proper name ' => ' Taylor ' ]],
[ ' developer ' => [ ' id ' => 2 , ' proper noun ' => ' Abigail ' ]],
];
$names = Arr :: pluck ( $array , ' programmer.name ' );
// ['Taylor', 'Abigail']
Y'all may likewise specify how you wish the resulting list to be keyed:
use Illuminate\Support\ Arr ;
$names = Arr :: pluck ( $array , ' programmer.proper name ' , ' developer.id ' );
// [1 => 'Taylor', 2 => 'Abigail']
Arr::prepend()
The Arr::prepend
method will push button an item onto the beginning of an array:
utilize Illuminate\Support\ Arr ;
$array = [ ' one ' , ' two ' , ' three ' , ' 4 ' ];
$array = Arr :: prepend ( $array , ' zero ' );
// ['cypher', 'one', 'two', 'three', '4']
If needed, you may specify the key that should exist used for the value:
use Illuminate\Support\ Arr ;
$assortment = [ ' price ' => 100 ];
$assortment = Arr :: prepend ( $assortment , ' Desk-bound ' , ' name ' );
// ['name' => 'Desk', 'cost' => 100]
Arr::pull()
The Arr::pull
method returns and removes a fundamental / value pair from an array:
employ Illuminate\Support\ Arr ;
$array = [ ' proper name ' => ' Desk-bound ' , ' price ' => 100 ];
$name = Arr :: pull ( $array , ' name ' );
// $name: Desk
// $array: ['cost' => 100]
A default value may be passed every bit the third argument to the method. This value volition exist returned if the key doesn't exist:
utilize Illuminate\Support\ Arr ;
$value = Arr :: pull ( $array , $cardinal , $default );
Arr::query()
The Arr::query
method converts the array into a query cord:
use Illuminate\Back up\ Arr ;
$array = [
' name ' => ' Taylor ' ,
' society ' => [
' cavalcade ' => ' created_at ' ,
' direction ' => ' desc '
]
];
Arr :: query ( $array );
// name=Taylor&order[column]=created_at&social club[direction]=desc
Arr::random()
The Arr::random
method returns a random value from an array:
use Illuminate\Support\ Arr ;
$assortment = [ i , 2 , 3 , four , 5 ];
$random = Arr :: random ( $array );
// four - (retrieved randomly)
Yous may likewise specify the number of items to return as an optional 2nd argument. Note that providing this argument will return an array even if only 1 item is desired:
apply Illuminate\Support\ Arr ;
$items = Arr :: random ( $array , ii );
// [ii, 5] - (retrieved randomly)
Arr::set up()
The Arr::gear up
method sets a value within a deeply nested assortment using "dot" notation:
use Illuminate\Back up\ Arr ;
$array = [ ' products ' => [ ' desk ' => [ ' price ' => 100 ]]];
Arr :: fix ( $assortment , ' products.desk.price ' , 200 );
// ['products' => ['desk-bound' => ['price' => 200]]]
Arr::shuffle()
The Arr::shuffle
method randomly shuffles the items in the array:
employ Illuminate\Support\ Arr ;
$array = Arr :: shuffle ([ 1 , 2 , 3 , 4 , 5 ]);
// [3, 2, 5, 1, four] - (generated randomly)
Arr::sort()
The Arr::sort
method sorts an array by its values:
employ Illuminate\Support\ Arr ;
$assortment = [ ' Desk-bound ' , ' Tabular array ' , ' Chair ' ];
$sorted = Arr :: sort ( $array );
// ['Chair', 'Desk-bound', 'Table']
Yous may likewise sort the array past the results of a given closure:
use Illuminate\Support\ Arr ;
$array = [
[ ' name ' => ' Desk ' ],
[ ' name ' => ' Tabular array ' ],
[ ' proper noun ' => ' Chair ' ],
];
$sorted = array_values ( Arr :: sort ($ assortment , function ( $ value ) {
return $ value [ ' proper name ' ];
}));
/*
[
['name' => 'Chair'],
['name' => 'Desk'],
['name' => 'Table'],
]
*/
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 ' , ' Blood-red ' , ' JavaScript ' ],
[ ' one ' => 1 , ' two ' => two , ' three ' => 3 ],
];
$sorted = Arr :: sortRecursive ( $array );
/*
[
['JavaScript', 'PHP', 'Scarlet'],
['one' => one, 'three' => three, 'two' => ii],
['Li', 'Roman', 'Taylor'],
]
*/
Arr::toCssClasses()
The Arr::toCssClasses
conditionally compiles a CSS class string. The method accepts an assortment of classes where the assortment key contains the class or classes y'all wish to add, while the value is a boolean expression. If the array element has a numeric key, it volition always be included in the rendered course list:
use Illuminate\Support\ Arr ;
$isActive = faux ;
$hasError = true ;
$array = [ ' p-4 ' , ' font-assuming ' => $isActive , ' bg-cherry-red ' => $hasError ];
$classes = Arr :: toCssClasses ( $array );
/*
'p-4 bg-scarlet'
*/
This method powers Laravel'due south functionality allowing merging classes with a Blade component's aspect pocketbook as well equally the @class
Blade directive.
Arr::undot()
The Arr::undot
method expands a unmarried-dimensional assortment that uses "dot" notation into a multi-dimensional array:
use Illuminate\Back up\ Arr ;
$array = [
' user.proper noun ' => ' Kevin Malone ' ,
' user.occupation ' => ' Accountant ' ,
];
$assortment = Arr :: undot ( $array );
// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]
Arr::where()
The Arr::where
method filters an array using the given closure:
use Illuminate\Back up\ Arr ;
$assortment = [ 100 , ' 200 ' , 300 , ' 400 ' , 500 ];
$filtered = Arr :: where ( $array , function ( $value , $key ) {
return is_string ($ value );
});
// [i => '200', 3 => '400']
Arr::whereNotNull()
The Arr::whereNotNull
method removes all aught
values from the given array:
apply Illuminate\Support\ Arr ;
$array = [ 0 , zip ];
$filtered = Arr :: whereNotNull ( $array );
// [0 => 0]
Arr::wrap()
The Arr::wrap
method wraps the given value in an assortment. If the given value is already an assortment it volition be returned without modification:
utilise Illuminate\Back up\ Arr ;
$string = ' Laravel ' ;
$array = Arr :: wrap ( $string );
// ['Laravel']
If the given value is goose egg
, an empty array will be returned:
use Illuminate\Support\ Arr ;
$array = Arr :: wrap ( nix );
// []
data_fill()
The data_fill
part sets a missing value within a nested array or object using "dot" note:
$data = [ ' products ' => [ ' desk ' => [ ' price ' => 100 ]]];
data_fill ($ data , ' products.desk.cost ' , 200 );
// ['products' => ['desk' => ['cost' => 100]]]
data_fill ($ data , ' products.desk.discount ' , ten );
// ['products' => ['desk' => ['price' => 100, 'discount' => x]]]
This function besides accepts asterisks as wildcards and will fill the target appropriately:
$data = [
' products ' => [
[ ' proper name ' => ' Desk-bound 1 ' , ' price ' => 100 ],
[ ' name ' => ' Desk 2 ' ],
],
];
data_fill ($ data , ' products.*.price ' , 200 );
/*
[
'products' => [
['proper noun' => '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 ]]];
$toll = data_get ($ data , ' products.desk.cost ' );
// 100
The data_get
office also accepts a default value, which will be returned if the specified key is not plant:
$discount = data_get ($ information , ' products.desk-bound.discount ' , 0 );
// 0
The role likewise accepts wildcards using asterisks, which may target any key of the assortment or object:
$data = [
' production-one ' => [ ' name ' => ' Desk 1 ' , ' toll ' => 100 ],
' product-two ' => [ ' name ' => ' Desk-bound 2 ' , ' cost ' => 150 ],
];
data_get ($ data , ' *.proper name ' );
// ['Desk ane', 'Desk 2'];
data_set()
The data_set
role sets a value within a nested array or object using "dot" annotation:
$information = [ ' products ' => [ ' desk ' => [ ' price ' => 100 ]]];
data_set ($ data , ' products.desk.price ' , 200 );
// ['products' => ['desk' => ['price' => 200]]]
This function also accepts wildcards using asterisks and will fix values on the target accordingly:
$information = [
' products ' => [
[ ' name ' => ' Desk-bound ane ' , ' toll ' => 100 ],
[ ' name ' => ' Desk-bound two ' , ' price ' => 150 ],
],
];
data_set ($ data , ' products.*.price ' , 200 );
/*
[
'products' => [
['name' => 'Desk one', 'price' => 200],
['name' => 'Desk 2', 'cost' => 200],
],
]
*/
By default, whatsoever existing values are overwritten. If you wish to only set a value if it doesn't exist, you may pass false
equally the fourth argument to the function:
$information = [ ' products ' => [ ' desk ' => [ ' price ' => 100 ]]];
data_set ($ data , ' products.desk.price ' , 200 , $ overwrite = simulated );
// ['products' => ['desk' => ['toll' => 100]]]
caput()
The caput
function returns the starting time element in the given array:
$array = [ 100 , 200 , 300 ];
$starting time = head ($ array );
// 100
last()
The final
function returns the last element in the given assortment:
$assortment = [ 100 , 200 , 300 ];
$final = last ($ array );
// 300
Paths
app_path()
The app_path
function returns the fully qualified path to your awarding's app
directory. You may also use the app_path
role to generate a fully qualified path to a file relative to the awarding directory:
$path = app_path ();
$path = app_path ( ' Http/Controllers/Controller.php ' );
base_path()
The base_path
function returns the fully qualified path to your application's root directory. 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 your awarding's config
directory. You may also use the config_path
function to generate a fully qualified path to a given file within the application'southward configuration directory:
$path = config_path ();
$path = config_path ( ' app.php ' );
database_path()
The database_path
part returns the fully qualified path to your awarding's database
directory. You may also use the database_path
role to generate a fully qualified path to a given file within the database directory:
$path = database_path ();
$path = database_path ( ' factories/UserFactory.php ' );
lang_path()
The lang_path
function returns the fully qualified path to your application's lang
directory. You may as well use the lang_path
function to generate a fully qualified path to a given file inside the directory:
$path = lang_path ();
$path = lang_path ( ' en/messages.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 your application'due south public
directory. Y'all 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 your application's resources
directory. You may too 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
role returns the fully qualified path to your application'due south storage
directory. You may too utilise the storage_path
function to generate a fully qualified path to a given file inside the storage directory:
$path = storage_path ();
$path = storage_path ( ' app/file.txt ' );
Strings
__()
The __
function translates the given translation string or translation central using your localization files:
echo __ ( ' Welcome to our awarding ' );
repeat __ ( ' messages.welcome ' );
If the specified translation cord or central does not exist, the __
function will render the given value. Then, using the example above, the __
function would return messages.welcome
if that translation fundamental does not exist.
class_basename()
The class_basename
function returns the course name of the given class with the course's namespace removed:
$class = class_basename ( ' Foo\Bar\Baz ' );
// Baz
e()
The e
function runs PHP'south htmlspecialchars
part with the double_encode
choice prepare to truthful
by default:
echo e ( ' <html>foo</html> ' );
// <html>foo</html>
preg_replace_array()
The preg_replace_array
function replaces a given blueprint in the string sequentially using an array:
$string = ' The result will take identify between :kickoff and :stop ' ;
$replaced = preg_replace_array ( '/ : [ a-z_ ] + /' , [ ' 8:30 ' , ' 9:00 ' ], $ string );
// The event will accept place between 8:30 and ix:00
Str::subsequently()
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 inside the string:
use Illuminate\Support\ Str ;
$piece = Str :: after ( ' This is my name ' , ' This is ' );
// ' my name'
Str::afterLast()
The Str::afterLast
method returns everything afterward the last occurrence of the given value in a string. The entire string volition be returned if the value does non exist within the cord:
use Illuminate\Back up\ Str ;
$slice = Str :: afterLast ( ' App\Http\Controllers\Controller ' , ' \\ ' );
// 'Controller'
Str::ascii()
The Str::ascii
method will attempt to transliterate the string into an ASCII value:
use Illuminate\Support\ Str ;
$slice = Str :: ascii ( ' û ' );
// 'u'
Str::before()
The Str::before
method returns everything before the given value in a cord:
use Illuminate\Support\ Str ;
$slice = Str :: earlier ( ' This is my name ' , ' my proper noun ' );
// 'This is '
Str::beforeLast()
The Str::beforeLast
method returns everything earlier the last occurrence of the given value in a string:
use Illuminate\Support\ Str ;
$piece = Str :: beforeLast ( ' This is my name ' , ' is ' );
// 'This '
Str::between()
The Str::between
method returns the portion of a string between 2 values:
employ Illuminate\Support\ Str ;
$slice = Str :: between ( ' This is my name ' , ' This ' , ' name ' );
// ' is my '
Str::betweenFirst()
The Str::betweenFirst
method returns the smallest possible portion of a string between ii values:
utilise Illuminate\Support\ Str ;
$slice = Str :: betweenFirst ( ' [a] bc [d] ' , ' [ ' , ' ] ' );
// 'a'
Str::camel()
The Str::camel
method converts the given cord to camelCase
:
use Illuminate\Back up\ Str ;
$converted = Str :: camel ( ' foo_bar ' );
// fooBar
Str::contains()
The Str::contains
method determines if the given string contains the given value. This method is example sensitive:
employ Illuminate\Back up\ Str ;
$contains = Str :: contains ( ' This is my name ' , ' my ' );
// true
Y'all may also pass an array of values to make up one's mind if the given string contains any of the values in the array:
use Illuminate\Support\ Str ;
$contains = Str :: contains ( ' This is my proper noun ' , [ ' my ' , ' foo ' ]);
// true
Str::containsAll()
The Str::containsAll
method determines if the given string contains all of the values in a given array:
utilize Illuminate\Support\ Str ;
$containsAll = Str :: containsAll ( ' This is my proper name ' , [ ' my ' , ' proper name ' ]);
// true
Str::endsWith()
The Str::endsWith
method determines if the given string ends with the given value:
utilize Illuminate\Support\ Str ;
$event = Str :: endsWith ( ' This is my proper name ' , ' name ' );
// true
Yous may also pass an array of values to determine if the given string ends with whatsoever of the values in the array:
use Illuminate\Back up\ Str ;
$consequence = Str :: endsWith ( ' This is my name ' , [ ' name ' , ' foo ' ]);
// truthful
$result = Str :: endsWith ( ' This is my name ' , [ ' this ' , ' foo ' ]);
// imitation
Str::excerpt()
The Str::excerpt
method extracts an excerpt from a given cord that matches the first example of a phrase within that string:
use Illuminate\Support\ Str ;
$excerpt = Str :: excerpt ( ' This is my name ' , ' my ' , [
' radius ' => iii
]);
// '...is my na...'
The radius
option, which defaults to 100
, allows yous to ascertain the number of characters that should appear on each side of the truncated string.
In addition, you may use the omission
choice to define the string that volition be prepended and appended to the truncated cord:
use Illuminate\Support\ Str ;
$excerpt = Str :: excerpt ( ' This is my name ' , ' name ' , [
' radius ' => three ,
' omission ' => ' (...) '
]);
// '(...) my proper noun'
Str::stop()
The Str::finish
method adds a unmarried instance of the given value to a string if information technology does not already end with that value:
use Illuminate\Support\ Str ;
$adjusted = Str :: cease ( ' this/string ' , ' / ' );
// this/string/
$adjusted = Str :: finish ( ' this/string/ ' , ' / ' );
// this/string/
Str::headline()
The Str::headline
method will convert strings delimited by casing, hyphens, or underscores into a space delimited cord with each give-and-take's first letter capitalized:
utilize Illuminate\Back up\ Str ;
$headline = Str :: headline ( ' steve_jobs ' );
// Steve Jobs
$headline = Str :: headline ( ' EmailNotificationSent ' );
// Email Notification Sent
Str::is()
The Str::is
method determines if a given string matches a given pattern. Asterisks may be used as wildcard values:
utilize Illuminate\Support\ Str ;
$matches = Str :: is ( ' foo* ' , ' foobar ' );
// truthful
$matches = Str :: is ( ' baz* ' , ' foobar ' );
// false
Str::isAscii()
The Str::isAscii
method determines if a given string is seven bit ASCII:
utilise Illuminate\Back up\ Str ;
$isAscii = Str :: isAscii ( ' Taylor ' );
// true
$isAscii = Str :: isAscii ( ' ü ' );
// imitation
Str::isUuid()
The Str::isUuid
method determines if the given cord is a valid UUID:
utilise Illuminate\Support\ Str ;
$isUuid = Str :: isUuid ( ' a0a2a2d2-0b87-4a18-83f2-2529882be2de ' );
// true
$isUuid = Str :: isUuid ( ' laravel ' );
// faux
Str::kebab()
The Str::kebab
method converts the given string to kebab-example
:
employ Illuminate\Support\ Str ;
$converted = Str :: kebab ( ' fooBar ' );
// foo-bar
Str::lcfirst()
The Str::lcfirst
method returns the given string with the first character lowercased:
use Illuminate\Support\ Str ;
$string = Str :: lcfirst ( ' Foo Bar ' );
// foo Bar
Str::length()
The Str::length
method returns the length of the given string:
apply Illuminate\Support\ Str ;
$length = Str :: length ( ' Laravel ' );
// 7
Str::limit()
The Str::limit
method truncates the given string to the specified length:
use Illuminate\Support\ Str ;
$truncated = Str :: limit ( ' The quick brown play a trick on jumps over the lazy domestic dog ' , 20 );
// The quick chocolate-brown fox...
You may pass a third argument to the method to change the string that volition be appended to the stop of the truncated cord:
use Illuminate\Support\ Str ;
$truncated = Str :: limit ( ' The quick brown fox jumps over the lazy dog ' , 20 , ' (...) ' );
// The quick brown fox (...)
Str::lower()
The Str::lower
method converts the given string to lowercase:
apply Illuminate\Support\ Str ;
$converted = Str :: lower ( ' LARAVEL ' );
// laravel
Str::markdown()
The Str::markdown
method converts GitHub flavored Markdown into HTML using CommonMark:
use Illuminate\Support\ Str ;
$html = Str :: markdown ( ' # Laravel ' );
// <h1>Laravel</h1>
$html = Str :: markdown ( ' # Taylor <b>Otwell</b> ' , [
' html_input ' => ' strip ' ,
]);
// <h1>Taylor Otwell</h1>
Str::mask()
The Str::mask
method masks a portion of a string with a repeated grapheme, and may be used to obfuscate segments of strings such every bit email addresses and telephone numbers:
utilize Illuminate\Back up\ Str ;
$string = Str :: mask ( ' [e-mail protected] ' , ' * ' , 3 );
// tay***************
If needed, you provide a negative number equally the third argument to the mask
method, which will instruct the method to begin masking at the given distance from the terminate of the string:
$string = Str :: mask ( ' [electronic mail protected] ' , ' * ' , - xv , 3 );
// tay***@instance.com
Str::orderedUuid()
The Str::orderedUuid
method generates a "timestamp first" UUID that may be efficiently stored in an indexed database cavalcade. Each UUID that is generated using this method volition be sorted after UUIDs previously generated using the method:
apply Illuminate\Support\ Str ;
render ( string ) Str :: orderedUuid ();
Str::padBoth()
The Str::padBoth
method wraps PHP's str_pad
role, padding both sides of a string with another string until the concluding string reaches a desired length:
use Illuminate\Support\ Str ;
$padded = Str :: padBoth ( ' James ' , x , ' _ ' );
// '__James___'
$padded = Str :: padBoth ( ' James ' , 10 );
// ' James '
Str::padLeft()
The Str::padLeft
method wraps PHP'southward str_pad
function, padding the left side of a string with another string until the final string reaches a desired length:
use Illuminate\Back up\ Str ;
$padded = Str :: padLeft ( ' James ' , 10 , ' -= ' );
// '-=-=-James'
$padded = Str :: padLeft ( ' James ' , x );
// ' James'
Str::padRight()
The Str::padRight
method wraps PHP'due south str_pad
function, padding the right side of a string with another string until the final string reaches a desired length:
use Illuminate\Support\ Str ;
$padded = Str :: padRight ( ' James ' , x , ' - ' );
// 'James-----'
$padded = Str :: padRight ( ' James ' , 10 );
// 'James '
Str::plural()
The Str::plural
method converts a singular word string to its plural course. This function currently but supports the English language:
apply Illuminate\Support\ Str ;
$plural = Str :: plural ( ' car ' );
// cars
$plural = Str :: plural ( ' child ' );
// children
You may provide an integer every bit a second argument to the function to call back the atypical or plural form of the string:
utilise Illuminate\Support\ Str ;
$plural = Str :: plural ( ' child ' , ii );
// children
$singular = Str :: plural ( ' child ' , 1 );
// child
Str::pluralStudly()
The Str::pluralStudly
method converts a singular word cord formatted in studly caps case to its plural form. This function currently but supports the English language:
employ Illuminate\Support\ Str ;
$plural = Str :: pluralStudly ( ' VerifiedHuman ' );
// VerifiedHumans
$plural = Str :: pluralStudly ( ' UserFeedback ' );
// UserFeedback
You may provide an integer as a 2nd argument to the office to retrieve the singular or plural form of the cord:
use Illuminate\Support\ Str ;
$plural = Str :: pluralStudly ( ' VerifiedHuman ' , ii );
// VerifiedHumans
$atypical = Str :: pluralStudly ( ' VerifiedHuman ' , one );
// VerifiedHuman
Str::random()
The Str::random
method generates a random string of the specified length. This function uses PHP'due south random_bytes
part:
use Illuminate\Support\ Str ;
$random = Str :: random ( 40 );
Str::remove()
The Str::remove
method removes the given value or array of values from the string:
use Illuminate\Back up\ Str ;
$string = ' Peter Piper picked a peck of pickled peppers. ' ;
$removed = Str :: remove ( ' e ' , $cord );
// Ptr Pipr pickd a pck of pickld ppprs.
You may also pass simulated
as a tertiary statement to the remove
method to ignore case when removing strings.
Str::replace()
The Str::replace
method replaces a given string within the string:
use Illuminate\Back up\ Str ;
$string = ' Laravel 8.x ' ;
$replaced = Str :: replace ( ' 8.x ' , ' nine.ten ' , $cord );
// Laravel 9.x
Str::replaceArray()
The Str::replaceArray
method replaces a given value in the string sequentially using an array:
use Illuminate\Support\ Str ;
$string = ' The event volition have place between ? and ? ' ;
$replaced = Str :: replaceArray ( ' ? ' , [ ' 8:xxx ' , ' 9:00 ' ], $string );
// The event will accept place betwixt 8:30 and 9:00
Str::replaceFirst()
The Str::replaceFirst
method replaces the first occurrence of a given value in a string:
utilise Illuminate\Support\ Str ;
$replaced = Str :: replaceFirst ( ' the ' , ' a ' , ' the quick chocolate-brown trick jumps over the lazy dog ' );
// a quick brown pull a fast one on jumps over the lazy domestic dog
Str::replaceLast()
The Str::replaceLast
method replaces the last occurrence of a given value in a string:
utilize Illuminate\Support\ Str ;
$replaced = Str :: replaceLast ( ' the ' , ' a ' , ' the quick brown trick jumps over the lazy dog ' );
// the quick brownish fox jumps over a lazy canis familiaris
Str::contrary()
The Str::opposite
method reverses the given string:
apply Illuminate\Support\ Str ;
$reversed = Str :: opposite ( ' Hello Globe ' );
// dlroW olleH
Str::atypical()
The Str::atypical
method converts a string to its singular form. This role currently but supports the English language linguistic communication:
use Illuminate\Support\ Str ;
$singular = Str :: singular ( ' cars ' );
// car
$singular = Str :: singular ( ' children ' );
// child
Str::slug()
The Str::slug
method generates a URL friendly "slug" from the given cord:
use Illuminate\Support\ Str ;
$slug = Str :: slug ( ' Laravel 5 Framework ' , ' - ' );
// laravel-5-framework
Str::snake()
The Str::snake
method converts the given string to snake_case
:
use Illuminate\Support\ Str ;
$converted = Str :: ophidian ( ' fooBar ' );
// foo_bar
$converted = Str :: serpent ( ' fooBar ' , ' - ' );
// foo-bar
Str::offset()
The Str::commencement
method adds a single instance of the given value to a string if information technology does not already start with that value:
utilise Illuminate\Back up\ Str ;
$adjusted = Str :: start ( ' this/string ' , ' / ' );
// /this/cord
$adjusted = Str :: start ( ' /this/cord ' , ' / ' );
// /this/string
Str::startsWith()
The Str::startsWith
method determines if the given cord begins with the given value:
employ Illuminate\Back up\ Str ;
$result = Str :: startsWith ( ' This is my proper name ' , ' This ' );
// truthful
If an array of possible values is passed, the startsWith
method will render true
if the string begins with whatever of the given values:
$issue = Str :: startsWith ( ' This is my name ' , [ ' This ' , ' That ' , ' In that location ' ]);
// true
Str::studly()
The Str::studly
method converts the given string to StudlyCase
:
use Illuminate\Support\ Str ;
$converted = Str :: studly ( ' foo_bar ' );
// FooBar
Str::substr()
The Str::substr
method returns the portion of cord specified by the showtime and length parameters:
use Illuminate\Support\ Str ;
$converted = Str :: substr ( ' The Laravel Framework ' , four , 7 );
// Laravel
Str::substrCount()
The Str::substrCount
method returns the number of occurrences of a given value in the given cord:
use Illuminate\Support\ Str ;
$count = Str :: substrCount ( ' If you lot like ice cream, you volition like snowfall cones. ' , ' similar ' );
// 2
Str::substrReplace()
The Str::substrReplace
method replaces text inside a portion of a string, starting at the position specified by the third argument and replacing the number of characters specified by the quaternary statement. Passing 0
to the method's 4th statement volition insert the cord at the specified position without replacing any of the existing characters in the string:
use Illuminate\Support\ Str ;
$result = Str :: substrReplace ( ' 1300 ' , ' : ' , ii );
// 13:
$consequence = Str :: substrReplace ( ' 1300 ' , ' : ' , 2 , 0 );
// 13:00
Str::bandy()
The Str::swap
method replaces multiple values in the given cord using PHP'due south strtr
role:
employ Illuminate\Support\ Str ;
$cord = Str :: swap ([
' Tacos ' => ' Burritos ' ,
' groovy ' => ' fantastic ' ,
], ' Tacos are keen! ' );
// Burritos are fantastic!
Str::championship()
The Str::championship
method converts the given string to Title Case
:
utilize Illuminate\Support\ Str ;
$converted = Str :: title ( ' a nice title uses the correct case ' );
// A Nice Title Uses The Correct Case
Str::toHtmlString()
The Str::toHtmlString
method converts the string instance to an instance of Illuminate\Support\HtmlString
, which may exist displayed in Blade templates:
employ Illuminate\Support\ Str ;
$htmlString = Str :: of ( ' Nuno Maduro ' ) -> toHtmlString ();
Str::ucfirst()
The Str::ucfirst
method returns the given string with the start character capitalized:
use Illuminate\Support\ Str ;
$string = Str :: ucfirst ( ' foo bar ' );
// Foo bar
Str::ucsplit()
The Str::ucsplit
method splits the given string into an array by capital letter characters:
use Illuminate\Support\ Str ;
$segments = Str :: ucsplit ( ' FooBar ' );
// [0 => 'Foo', 1 => 'Bar']
Str::upper()
The Str::upper
method converts the given string to uppercase:
apply Illuminate\Back up\ Str ;
$string = Str :: upper ( ' laravel ' );
// LARAVEL
Str::uuid()
The Str::uuid
method generates a UUID (version 4):
use Illuminate\Support\ Str ;
return ( string ) Str :: uuid ();
Str::wordCount()
The Str::wordCount
method returns the number of words that a string contains:
use Illuminate\Support\ Str ;
Str :: wordCount ( ' Hello, world! ' ); // 2
Str::words()
The Str::words
method limits the number of words in a string. An additional string may be passed to this method via its 3rd argument to specify which string should exist appended to the end of the truncated string:
utilise Illuminate\Back up\ Str ;
return Str :: words ( ' Perfectly counterbalanced, as all things should be. ' , 3 , ' >>> ' );
// Perfectly balanced, equally >>>
str()
The str
function returns a new Illuminate\Support\Stringable
case of the given string. This function is equivalent to the Str::of
method:
$string = str ( ' Taylor ' ) -> append ( ' Otwell ' );
// 'Taylor Otwell'
If no argument is provided to the str
office, the part returns an instance of Illuminate\Back up\Str
:
$snake = str () -> snake ( ' FooBar ' );
// 'foo_bar'
trans()
The trans
part translates the given translation key using your localization files:
repeat trans ( ' messages.welcome ' );
If the specified translation primal does non exist, the trans
function will return the given fundamental. So, using the instance 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:
echo trans_choice ( ' messages.notifications ' , $ unreadCount );
If the specified translation central does non exist, the trans_choice
function volition return the given primal. So, using the case in a higher place, the trans_choice
function would return messages.notifications
if the translation key does not exist.
Fluent Strings
Fluent strings provide a more than fluent, object-oriented interface for working with string values, assuasive y'all to concatenation multiple cord operations together using a more readable syntax compared to traditional string operations.
after
The later
method returns everything after the given value in a string. The entire cord will be returned if the value does not be within the string:
use Illuminate\Support\ Str ;
$slice = Str :: of ( ' This is my name ' ) -> after ( ' This is ' );
// ' my name'
afterLast
The afterLast
method returns everything after the terminal occurrence of the given value in a string. The entire string will be returned if the value does not exist within the cord:
utilise Illuminate\Support\ Str ;
$slice = Str :: of ( ' App\Http\Controllers\Controller ' ) -> afterLast ( ' \\ ' );
// 'Controller'
append
The suspend
method appends the given values to the string:
utilise Illuminate\Support\ Str ;
$string = Str :: of ( ' Taylor ' ) -> append ( ' Otwell ' );
// 'Taylor Otwell'
ascii
The ascii
method volition try to transliterate the string into an ASCII value:
utilize Illuminate\Back up\ Str ;
$string = Str :: of ( ' ü ' ) -> ascii ();
// 'u'
basename
The basename
method will return the abaft name component of the given string:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' /foo/bar/baz ' ) -> basename ();
// 'baz'
If needed, you may provide an "extension" that will be removed from the trailing component:
utilise Illuminate\Support\ Str ;
$string = Str :: of ( ' /foo/bar/baz.jpg ' ) -> basename ( ' .jpg ' );
// 'baz'
before
The before
method returns everything before the given value in a string:
use Illuminate\Support\ Str ;
$slice = Str :: of ( ' This is my proper name ' ) -> earlier ( ' my name ' );
// 'This is '
beforeLast
The beforeLast
method returns everything before the last occurrence of the given value in a string:
utilize Illuminate\Support\ Str ;
$slice = Str :: of ( ' This is my name ' ) -> beforeLast ( ' is ' );
// 'This '
between
The between
method returns the portion of a string betwixt two values:
use Illuminate\Back up\ Str ;
$converted = Str :: of ( ' This is my name ' ) -> between ( ' This ' , ' name ' );
// ' is my '
betweenFirst
The betweenFirst
method returns the smallest possible portion of a string betwixt two values:
utilise Illuminate\Support\ Str ;
$converted = Str :: of ( ' [a] bc [d] ' ) -> betweenFirst ( ' [ ' , ' ] ' );
// 'a'
camel
The camel
method converts the given cord to camelCase
:
use Illuminate\Support\ Str ;
$converted = Str :: of ( ' foo_bar ' ) -> camel ();
// fooBar
contains
The contains
method determines if the given cord contains the given value. This method is example sensitive:
employ Illuminate\Back up\ Str ;
$contains = Str :: of ( ' This is my name ' ) -> contains ( ' my ' );
// true
You may as well pass an array of values to determine if the given string contains any of the values in the assortment:
employ Illuminate\Support\ Str ;
$contains = Str :: of ( ' This is my name ' ) -> contains ([ ' my ' , ' foo ' ]);
// truthful
containsAll
The containsAll
method determines if the given string contains all of the values in the given array:
employ Illuminate\Support\ Str ;
$containsAll = Str :: of ( ' This is my proper name ' ) -> containsAll ([ ' my ' , ' proper name ' ]);
// true
dirname
The dirname
method returns the parent directory portion of the given string:
apply Illuminate\Support\ Str ;
$cord = Str :: of ( ' /foo/bar/baz ' ) -> dirname ();
// '/foo/bar'
If necessary, y'all may specify how many directory levels you wish to trim from the string:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' /foo/bar/baz ' ) -> dirname ( 2 );
// '/foo'
excerpt
The extract
method extracts an excerpt from the string that matches the start instance of a phrase inside that string:
utilise Illuminate\Support\ Str ;
$excerpt = Str :: of ( ' This is my name ' ) -> excerpt ( ' my ' , [
' radius ' => 3
]);
// '...is my na...'
The radius
option, which defaults to 100
, allows yous to ascertain the number of characters that should announced on each side of the truncated cord.
In addition, you may use the omission
option to modify the cord that will be prepended and appended to the truncated string:
use Illuminate\Support\ Str ;
$excerpt = Str :: of ( ' This is my name ' ) -> extract ( ' proper noun ' , [
' radius ' => 3 ,
' omission ' => ' (...) '
]);
// '(...) my proper name'
endsWith
The endsWith
method determines if the given string ends with the given value:
use Illuminate\Back up\ Str ;
$result = Str :: of ( ' This is my name ' ) -> endsWith ( ' name ' );
// true
Yous may as well pass an assortment of values to determine if the given string ends with any of the values in the array:
use Illuminate\Back up\ Str ;
$result = Str :: of ( ' This is my name ' ) -> endsWith ([ ' name ' , ' foo ' ]);
// true
$result = Str :: of ( ' This is my name ' ) -> endsWith ([ ' this ' , ' foo ' ]);
// simulated
exactly
The exactly
method determines if the given string is an exact match with some other string:
apply Illuminate\Back up\ Str ;
$result = Str :: of ( ' Laravel ' ) -> exactly ( ' Laravel ' );
// truthful
explode
The explode
method splits the string by the given delimiter and returns a drove containing each section of the split string:
use Illuminate\Support\ Str ;
$collection = Str :: of ( ' foo bar baz ' ) -> explode ( ' ' );
// collect(['foo', 'bar', 'baz'])
finish
The finish
method adds a single instance of the given value to a cord if it does not already end with that value:
utilise Illuminate\Support\ Str ;
$adjusted = Str :: of ( ' this/string ' ) -> finish ( ' / ' );
// this/string/
$adjusted = Str :: of ( ' this/string/ ' ) -> finish ( ' / ' );
// this/string/
is
The is
method determines if a given cord matches a given blueprint. Asterisks may be used as wildcard values
utilize Illuminate\Support\ Str ;
$matches = Str :: of ( ' foobar ' ) -> is ( ' foo* ' );
// true
$matches = Str :: of ( ' foobar ' ) -> is ( ' baz* ' );
// false
isAscii
The isAscii
method determines if a given cord is an ASCII string:
use Illuminate\Back up\ Str ;
$result = Str :: of ( ' Taylor ' ) -> isAscii ();
// true
$effect = Str :: of ( ' ü ' ) -> isAscii ();
// false
isEmpty
The isEmpty
method determines if the given cord is empty:
employ Illuminate\Support\ Str ;
$result = Str :: of ( ' ' ) -> trim () -> isEmpty ();
// truthful
$result = Str :: of ( ' Laravel ' ) -> trim () -> isEmpty ();
// imitation
isNotEmpty
The isNotEmpty
method determines if the given cord is not empty:
utilise Illuminate\Support\ Str ;
$issue = Str :: of ( ' ' ) -> trim () -> isNotEmpty ();
// simulated
$event = Str :: of ( ' Laravel ' ) -> trim () -> isNotEmpty ();
// truthful
isUuid
The isUuid
method determines if a given string is a UUID:
use Illuminate\Support\ Str ;
$result = Str :: of ( ' 5ace9ab9-e9cf-4ec6-a19d-5881212a452c ' ) -> isUuid ();
// true
$result = Str :: of ( ' Taylor ' ) -> isUuid ();
// false
kebab
The kebab
method converts the given string to kebab-example
:
employ Illuminate\Back up\ Str ;
$converted = Str :: of ( ' fooBar ' ) -> kebab ();
// foo-bar
lcfirst
The lcfirst
method returns the given string with the kickoff character lowercased:
utilize Illuminate\Support\ Str ;
$string = Str :: of ( ' Foo Bar ' ) -> lcfirst ();
// foo Bar
length
The length
method returns the length of the given string:
use Illuminate\Back up\ Str ;
$length = Str :: of ( ' Laravel ' ) -> length ();
// 7
limit
The limit
method truncates the given string to the specified length:
use Illuminate\Support\ Str ;
$truncated = Str :: of ( ' The quick brown pull a fast one on jumps over the lazy dog ' ) -> limit ( 20 );
// The quick brown play a trick on...
Y'all may as well pass a second argument to change the cord that volition exist appended to the end of the truncated string:
utilize Illuminate\Support\ Str ;
$truncated = Str :: of ( ' The quick brown fox jumps over the lazy dog ' ) -> limit ( 20 , ' (...) ' );
// The quick chocolate-brown fox (...)
lower
The lower
method converts the given string to lowercase:
use Illuminate\Support\ Str ;
$result = Str :: of ( ' LARAVEL ' ) -> lower ();
// 'laravel'
ltrim
The ltrim
method trims the left side of the cord:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' Laravel ' ) -> ltrim ();
// 'Laravel '
$string = Str :: of ( '/ Laravel /' ) -> ltrim ( ' / ' );
// 'Laravel/'
markdown
The markdown
method converts GitHub flavored Markdown into HTML:
use Illuminate\Support\ Str ;
$html = Str :: of ( ' # Laravel ' ) -> markdown ();
// <h1>Laravel</h1>
$html = Str :: of ( ' # Taylor <b>Otwell</b> ' ) -> markdown ([
' html_input ' => ' strip ' ,
]);
// <h1>Taylor Otwell</h1>
mask
The mask
method masks a portion of a string with a repeated graphic symbol, and may exist used to obfuscate segments of strings such equally email addresses and phone numbers:
use Illuminate\Support\ Str ;
$cord = Str :: of ( ' [email protected] ' ) -> mask ( ' * ' , three );
// tay***************
If needed, yous provide a negative number as the 3rd argument to the mask
method, which will instruct the method to begin masking at the given altitude from the end of the string:
$cord = Str :: of ( ' [email protected] ' ) -> mask ( ' * ' , - 15 , iii );
// tay***@example.com
match
The match
method will render the portion of a string that matches a given regular expression pattern:
use Illuminate\Support\ Str ;
$consequence = Str :: of ( ' foo bar ' ) -> friction match ( '/ bar /' );
// 'bar'
$result = Str :: of ( ' foo bar ' ) -> friction match ( '/ foo (. * ) /' );
// 'bar'
matchAll
The matchAll
method will return a collection containing the portions of a string that match a given regular expression pattern:
employ Illuminate\Support\ Str ;
$result = Str :: of ( ' bar foo bar ' ) -> matchAll ( '/ bar /' );
// collect(['bar', 'bar'])
If you specify a matching group within the expression, Laravel volition return a collection of that group'southward matches:
employ Illuminate\Support\ Str ;
$result = Str :: of ( ' bar fun bar fly ' ) -> matchAll ( '/ f( \w * ) /' );
// collect(['united nations', 'ly']);
If no matches are plant, an empty collection volition exist returned.
padBoth
The padBoth
method wraps PHP's str_pad
office, padding both sides of a string with some other string until the last string reaches the desired length:
use Illuminate\Support\ Str ;
$padded = Str :: of ( ' James ' ) -> padBoth ( 10 , ' _ ' );
// '__James___'
$padded = Str :: of ( ' James ' ) -> padBoth ( 10 );
// ' James '
padLeft
The padLeft
method wraps PHP's str_pad
function, padding the left side of a string with another string until the concluding string reaches the desired length:
utilise Illuminate\Support\ Str ;
$padded = Str :: of ( ' James ' ) -> padLeft ( 10 , ' -= ' );
// '-=-=-James'
$padded = Str :: of ( ' James ' ) -> padLeft ( ten );
// ' James'
padRight
The padRight
method wraps PHP's str_pad
function, padding the correct side of a string with another string until the final string reaches the desired length:
use Illuminate\Back up\ Str ;
$padded = Str :: of ( ' James ' ) -> padRight ( x , ' - ' );
// 'James-----'
$padded = Str :: of ( ' James ' ) -> padRight ( 10 );
// 'James '
pipe
The pipage
method allows you lot to transform the string past passing its current value to the given callable:
use Illuminate\Support\ Str ;
$hash = Str :: of ( ' Laravel ' ) -> pipage ( ' md5 ' ) -> prepend ( ' Checksum: ' );
// 'Checksum: a5c95b86291ea299fcbe64458ed12702'
$closure = Str :: of ( ' foo ' ) -> pipe ( part ( $str ) {
render ' bar ' ;
});
// 'bar'
plural
The plural
method converts a singular word string to its plural form. This part currently but supports the English language:
use Illuminate\Support\ Str ;
$plural = Str :: of ( ' automobile ' ) -> plural ();
// cars
$plural = Str :: of ( ' child ' ) -> plural ();
// children
You may provide an integer as a second argument to the role to retrieve the singular or plural grade of the cord:
use Illuminate\Back up\ Str ;
$plural = Str :: of ( ' child ' ) -> plural ( 2 );
// children
$plural = Str :: of ( ' child ' ) -> plural ( 1 );
// kid
prepend
The prepend
method prepends the given values onto the string:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' Framework ' ) -> prepend ( ' Laravel ' );
// Laravel Framework
remove
The remove
method removes the given value or array of values from the cord:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' Arkansas is quite beautiful! ' ) -> remove ( ' quite ' );
// Arkansas is cute!
You may also pass imitation
as a second parameter to ignore instance when removing strings.
supervene upon
The replace
method replaces a given string within the cord:
use Illuminate\Support\ Str ;
$replaced = Str :: of ( ' Laravel 6.x ' ) -> replace ( ' 6.ten ' , ' 7.ten ' );
// Laravel 7.x
replaceArray
The replaceArray
method replaces a given value in the string sequentially using an array:
employ Illuminate\Support\ Str ;
$cord = ' The event will take place between ? and ? ' ;
$replaced = Str :: of ( $string ) -> replaceArray ( ' ? ' , [ ' 8:30 ' , ' 9:00 ' ]);
// The outcome will take place betwixt 8:30 and 9:00
replaceFirst
The replaceFirst
method replaces the first occurrence of a given value in a string:
use Illuminate\Support\ Str ;
$replaced = Str :: of ( ' the quick brown pull a fast one on jumps over the lazy canis familiaris ' ) -> replaceFirst ( ' the ' , ' a ' );
// a quick brown pull a fast one on jumps over the lazy dog
replaceLast
The replaceLast
method replaces the last occurrence of a given value in a cord:
utilise Illuminate\Support\ Str ;
$replaced = Str :: of ( ' the quick brown fox jumps over the lazy domestic dog ' ) -> replaceLast ( ' the ' , ' a ' );
// the quick brown flim-flam jumps over a lazy dog
replaceMatches
The replaceMatches
method replaces all portions of a string matching a blueprint with the given replacement string:
use Illuminate\Support\ Str ;
$replaced = Str :: of ( ' (+ane) 501-555-1000 ' ) -> replaceMatches ( '/ [^A-Za-z0-nine] ++ /' , '' )
// '15015551000'
The replaceMatches
method also accepts a closure that will exist invoked with each portion of the cord matching the given pattern, allowing you to perform the replacement logic within the closure and render the replaced value:
use Illuminate\Support\ Str ;
$replaced = Str :: of ( ' 123 ' ) -> replaceMatches ( '/ \d /' , function ( $lucifer ) {
return ' [ ' . $lucifer [ 0 ] . ' ] ' ;
});
// '[1][two][iii]'
rtrim
The rtrim
method trims the correct side of the given cord:
use Illuminate\Support\ Str ;
$cord = Str :: of ( ' Laravel ' ) -> rtrim ();
// ' Laravel'
$string = Str :: of ( '/ Laravel /' ) -> rtrim ( ' / ' );
// '/Laravel'
scan
The scan
method parses input from a string into a collection according to a format supported by the sscanf
PHP part:
apply Illuminate\Support\ Str ;
$collection = Str :: of ( ' filename.jpg ' ) -> browse ( ' %[^.].%s ' );
// collect(['filename', 'jpg'])
singular
The atypical
method converts a string to its singular grade. This function currently only supports the English language language:
use Illuminate\Support\ Str ;
$singular = Str :: of ( ' cars ' ) -> singular ();
// machine
$singular = Str :: of ( ' children ' ) -> singular ();
// child
slug
The slug
method generates a URL friendly "slug" from the given string:
apply Illuminate\Support\ Str ;
$slug = Str :: of ( ' Laravel Framework ' ) -> slug ( ' - ' );
// laravel-framework
serpent
The snake
method converts the given string to snake_case
:
use Illuminate\Back up\ Str ;
$converted = Str :: of ( ' fooBar ' ) -> snake ();
// foo_bar
split
The separate
method splits a string into a collection using a regular expression:
apply Illuminate\Support\ Str ;
$segments = Str :: of ( ' ane, two, iii ' ) -> split ( '/ [\s,] + /' );
// collect(["1", "two", "iii"])
starting time
The start
method adds a single example of the given value to a cord if it does not already start with that value:
utilise Illuminate\Support\ Str ;
$adjusted = Str :: of ( ' this/string ' ) -> start ( ' / ' );
// /this/cord
$adjusted = Str :: of ( ' /this/string ' ) -> kickoff ( ' / ' );
// /this/cord
startsWith
The startsWith
method determines if the given string begins with the given value:
use Illuminate\Support\ Str ;
$result = Str :: of ( ' This is my name ' ) -> startsWith ( ' This ' );
// true
studly
The studly
method converts the given cord to StudlyCase
:
use Illuminate\Support\ Str ;
$converted = Str :: of ( ' foo_bar ' ) -> studly ();
// FooBar
substr
The substr
method returns the portion of the string specified past the given start and length parameters:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' Laravel Framework ' ) -> substr ( 8 );
// Framework
$cord = Str :: of ( ' Laravel Framework ' ) -> substr ( 8 , 5 );
// Frame
substrReplace
The substrReplace
method replaces text within a portion of a string, starting at the position specified by the second statement and replacing the number of characters specified by the third argument. Passing 0
to the method's third statement will insert the cord at the specified position without replacing any of the existing characters in the string:
use Illuminate\Back up\ Str ;
$string = Str :: of ( ' 1300 ' ) -> substrReplace ( ' : ' , 2 );
// 13:
$string = Str :: of ( ' The Framework ' ) -> substrReplace ( ' Laravel ' , 3 , 0 );
// The Laravel Framework
swap
The swap
method replaces multiple values in the string using PHP's strtr
role:
utilize Illuminate\Back up\ Str ;
$string = Str :: of ( ' Tacos are great! ' )
-> swap ([
' Tacos ' => ' Burritos ' ,
' bang-up ' => ' fantastic ' ,
]);
// Burritos are fantastic!
tap
The tap
method passes the string to the given closure, assuasive you to examine and collaborate with the string while not affecting the string itself. The original cord is returned by the tap
method regardless of what is returned past the closure:
utilise Illuminate\Back up\ Str ;
$string = Str :: of ( ' Laravel ' )
-> append ( ' Framework ' )
-> tap ( function ( $cord ) {
dump ( ' Cord later append: ' . $ cord );
})
-> upper ();
// LARAVEL FRAMEWORK
test
The test
method determines if a string matches the given regular expression pattern:
utilise Illuminate\Support\ Str ;
$result = Str :: of ( ' Laravel Framework ' ) -> test ( '/ Laravel /' );
// true
title
The title
method converts the given string to Championship Case
:
use Illuminate\Support\ Str ;
$converted = Str :: of ( ' a prissy championship uses the correct case ' ) -> title ();
// A Nice Championship Uses The Correct Case
trim
The trim
method trims the given string:
utilise Illuminate\Back up\ Str ;
$cord = Str :: of ( ' Laravel ' ) -> trim ();
// 'Laravel'
$string = Str :: of ( '/ Laravel /' ) -> trim ( ' / ' );
// 'Laravel'
ucfirst
The ucfirst
method returns the given string with the first character capitalized:
employ Illuminate\Support\ Str ;
$string = Str :: of ( ' foo bar ' ) -> ucfirst ();
// Foo bar
ucsplit
The ucsplit
method splits the given cord into a collection by upper-case letter characters:
utilize Illuminate\Back up\ Str ;
$cord = Str :: of ( ' Foo Bar ' ) -> ucsplit ();
// collect(['Foo', 'Bar'])
upper
The upper
method converts the given cord to uppercase:
use Illuminate\Support\ Str ;
$adjusted = Str :: of ( ' laravel ' ) -> upper ();
// LARAVEL
when
The when
method invokes the given closure if a given condition is true
. The closure volition receive the fluent string instance:
employ Illuminate\Support\ Str ;
$string = Str :: of ( ' Taylor ' )
-> when ( true , function ( $string ) {
return $string -> append ( ' Otwell ' );
});
// 'Taylor Otwell'
If necessary, you may pass another closure every bit the tertiary parameter to the when
method. This closure volition execute if the status parameter evaluates to false
.
whenContains
The whenContains
method invokes the given closure if the string contains the given value. The closure will receive the fluent string instance:
utilise Illuminate\Support\ Str ;
$string = Str :: of ( ' tony stark ' )
-> whenContains ( ' tony ' , office ( $string ) {
return $string -> title ();
});
// 'Tony Stark'
If necessary, you may laissez passer another closure as the third parameter to the when
method. This closure will execute if the cord does not contain the given value.
You may also pass an array of values to determine if the given string contains whatever of the values in the array:
apply Illuminate\Support\ Str ;
$string = Str :: of ( ' tony stark ' )
-> whenContains ([ ' tony ' , ' blob ' ], function ( $string ) {
render $string -> championship ();
});
// Tony Stark
whenContainsAll
The whenContainsAll
method invokes the given closure if the string contains all of the given sub-strings. The closure volition receive the fluent string instance:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' tony stark ' )
-> whenContainsAll ([ ' tony ' , ' stark ' ], office ( $string ) {
return $string -> title ();
});
// 'Tony Stark'
If necessary, you may pass some other closure equally the third parameter to the when
method. This closure will execute if the condition parameter evaluates to simulated
.
whenEmpty
The whenEmpty
method invokes the given closure if the string is empty. If the closure returns a value, that value will too exist returned past the whenEmpty
method. If the closure does not return a value, the fluent string case volition be returned:
utilise Illuminate\Support\ Str ;
$cord = Str :: of ( ' ' ) -> whenEmpty ( role ( $string ) {
return $string -> trim () -> prepend ( ' Laravel ' );
});
// 'Laravel'
whenNotEmpty
The whenNotEmpty
method invokes the given closure if the string is not empty. If the closure returns a value, that value will also exist returned past the whenNotEmpty
method. If the closure does non return a value, the fluent string instance will be returned:
employ Illuminate\Support\ Str ;
$string = Str :: of ( ' Framework ' ) -> whenNotEmpty ( office ( $string ) {
return $string -> prepend ( ' Laravel ' );
});
// 'Laravel Framework'
whenStartsWith
The whenStartsWith
method invokes the given closure if the string starts with the given sub-string. The closure will receive the fluent string instance:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' disney world ' ) -> whenStartsWith ( ' disney ' , function ( $string ) {
return $cord -> title ();
});
// 'Disney World'
whenEndsWith
The whenEndsWith
method invokes the given closure if the string ends with the given sub-string. The closure volition receive the fluent string instance:
utilise Illuminate\Support\ Str ;
$string = Str :: of ( ' disney world ' ) -> whenEndsWith ( ' earth ' , part ( $cord ) {
return $cord -> title ();
});
// 'Disney World'
whenExactly
The whenExactly
method invokes the given closure if the string exactly matches the given string. The closure will receive the fluent string case:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' laravel ' ) -> whenExactly ( ' laravel ' , function ( $cord ) {
return $cord -> championship ();
});
// 'Laravel'
whenIs
The whenIs
method invokes the given closure if the string matches a given design. Asterisks may be used as wildcard values. The closure volition receive the fluent cord example:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' foo/bar ' ) -> whenIs ( ' foo/* ' , function ( $string ) {
render $string -> append ( ' /baz ' );
});
// 'foo/bar/baz'
whenIsAscii
The whenIsAscii
method invokes the given closure if the string is 7 flake ASCII. The closure will receive the fluent string instance:
use Illuminate\Support\ Str ;
$cord = Str :: of ( ' foo/bar ' ) -> whenIsAscii ( ' laravel ' , function ( $string ) {
return $string -> championship ();
});
// 'Laravel'
whenIsUuid
The whenIsUuid
method invokes the given closure if the cord is a valid UUID. The closure volition receive the fluent string instance:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' foo/bar ' ) -> whenIsUuid ( ' a0a2a2d2-0b87-4a18-83f2-2529882be2de ' , function ( $string ) {
render $string -> substr ( 0 , viii );
});
// 'a0a2a2d2'
whenTest
The whenTest
method invokes the given closure if the string matches the given regular expression. The closure will receive the fluent string instance:
use Illuminate\Support\ Str ;
$string = Str :: of ( ' laravel framework ' ) -> whenTest ( '/ laravel /' , function ( $string ) {
return $string -> title ();
});
// 'Laravel Framework'
wordCount
The wordCount
method returns the number of words that a string contains:
apply Illuminate\Back up\ Str ;
Str :: of ( ' Hello, earth! ' ) -> wordCount (); // 2
words
The words
method limits the number of words in a string. If necessary, you may specify an boosted string that will be appended to the truncated string:
use Illuminate\Back up\ Str ;
$string = Str :: of ( ' Perfectly balanced, as all things should be. ' ) -> words ( 3 , ' >>> ' );
// Perfectly counterbalanced, as >>>
URLs
action()
The activeness
role generates a URL for the given controller activeness:
use App\Http\Controllers\ HomeController ;
$url = activity ([ HomeController :: class , ' index ' ]);
If the method accepts route parameters, you may pass them as the second argument to the method:
$url = action ([ UserController :: class , ' profile ' ], [ ' id ' => 1 ]);
asset()
The asset
function generates a URL for an asset using the electric current scheme of the request (HTTP or HTTPS):
$url = asset ( ' img/photograph.jpg ' );
Yous can configure the asset URL host by setting the ASSET_URL
variable in your .env
file. This tin can be useful if you lot host your avails on an external service like Amazon S3 or another CDN:
// ASSET_URL=http://example.com/assets
$url = asset ( ' img/photo.jpg ' ); // http://example.com/assets/img/photo.jpg
road()
The route
function generates a URL for a given named route:
$url = road ( ' road.name ' );
If the road accepts parameters, y'all may pass them as the second argument to the function:
$url = route ( ' route.name ' , [ ' id ' => 1 ]);
By default, the road
function generates an absolute URL. If you lot wish to generate a relative URL, you may pass false
as the 3rd statement to the function:
$url = road ( ' route.name ' , [ ' id ' => ane ], false );
secure_asset()
The secure_asset
office generates a URL for an asset using HTTPS:
$url = secure_asset ( ' img/photo.jpg ' );
secure_url()
The secure_url
role generates a fully qualified HTTPS URL to the given path. Additional URL segments may be passed in the part's second statement:
$url = secure_url ( ' user/profile ' );
$url = secure_url ( ' user/contour ' , [ one ]);
to_route()
The to_route
office generates a redirect HTTP response for a given named route:
render to_route ( ' users.bear witness ' , [ ' user ' => i ]);
If necessary, you may pass the HTTP condition lawmaking that should be assigned to the redirect and whatsoever additional response headers equally the third and fourth arguments to the to_route
method:
return to_route ( ' users.show ' , [ ' user ' => 1 ], 302 , [ ' X-Framework ' => ' Laravel ' ]);
url()
The url
function generates a fully qualified URL to the given path:
$url = url ( ' user/profile ' );
$url = url ( ' user/profile ' , [ one ]);
If no path is provided, an Illuminate\Routing\UrlGenerator
example is returned:
$current = url () -> current ();
$total = url () -> total ();
$previous = url () -> previous ();
Miscellaneous
abort()
The abort
function throws an HTTP exception which will be rendered past the exception handler:
arrest ( 403 );
You lot may also provide the exception'south message and custom HTTP response headers that should be sent to the browser:
abort ( 403 , ' Unauthorized. ' , $ headers );
abort_if()
The abort_if
role throws an HTTP exception if a given boolean expression evaluates to true
:
abort_if ( ! Auth :: user () -> isAdmin (), 403 );
Like the abort
method, y'all may besides provide the exception's response text every bit the tertiary argument and an array of custom response headers every bit the fourth argument to the office.
abort_unless()
The abort_unless
part throws an HTTP exception if a given boolean expression evaluates to false
:
abort_unless ( Auth :: user () -> isAdmin (), 403 );
Like the abort
method, you may as well provide the exception'due south response text every bit the 3rd argument and an array of custom response headers every bit the fourth statement to the function.
app()
The app
function returns the service container instance:
$container = app ();
You may pass a course or interface proper name to resolve it from the container:
$api = app ( ' HelpSpot\API ' );
auth()
The auth
function returns an authenticator instance. You lot may use information technology as an alternative to the Auth
facade:
$user = auth () -> user ();
If needed, you may specify which baby-sit instance you would similar to access:
$user = auth ( ' admin ' ) -> user ();
back()
The dorsum
function generates a redirect HTTP response to the user's previous location:
return dorsum ($ status = 302 , $ headers = [], $ fallback = ' / ' );
return back ();
bcrypt()
The bcrypt
function hashes the given value using Bcrypt. You lot may apply this function as an culling to the Hash
facade:
$countersign = bcrypt ( ' my-hugger-mugger-password ' );
blank()
The blank
part determines whether the given value is "blank":
blank ( '' );
blank ( ' ' );
blank ( cipher );
bare ( collect ());
// true
blank ( 0 );
blank ( true );
blank ( faux );
// false
For the changed of blank
, see the filled
method.
broadcast()
The broadcast
function broadcasts the given event to its listeners:
broadcast ( new UserRegistered ($ user ));
broadcast ( new UserRegistered ($ user )) -> toOthers ();
enshroud()
The enshroud
function may exist used to get values from the enshroud. If the given primal does not exist in the cache, an optional default value will exist returned:
$value = cache ( ' key ' );
$value = cache ( ' key ' , ' default ' );
You may add items to the cache by passing an array of key / value pairs to the role. Y'all should also laissez passer the number of seconds or duration the cached value should exist considered valid:
enshroud ([ ' primal ' => ' value ' ], 300 );
cache ([ ' cardinal ' => ' value ' ], at present () -> addSeconds ( x ));
class_uses_recursive()
The class_uses_recursive
function returns all traits used by a class, including traits used by all of its parent classes:
$traits = class_uses_recursive ( App \ Models \ User :: class );
collect()
The collect
function creates a collection instance from the given value:
$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:
$value = config ( ' app.timezone ' );
$value = config ( ' app.timezone ' , $ default );
Yous may ready configuration variables at runtime by passing an assortment of fundamental / value pairs. However, note that this role only affects the configuration value for the current request and does not update your bodily configuration values:
config ([ ' app.debug ' => true ]);
cookie()
The cookie
role creates a new cookie instance:
$cookie = cookie ( ' name ' , ' value ' , $ minutes );
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_field () }}
csrf_token()
The csrf_token
office retrieves the value of the current CSRF token:
$token = csrf_token ();
decrypt()
The decrypt
function decrypts the given value. You may utilize this function as an alternative to the Crypt
facade:
$password = decrypt ($ value );
dd()
The dd
function dumps the given variables and ends execution of the script:
dd ($ value );
dd ($ value1 , $ value2 , $ value3 , ... );
If you do not want to halt the execution of your script, use the dump
office instead.
dispatch()
The acceleration
function pushes the given job onto the Laravel task queue:
dispatch ( new App \ Jobs \ SendEmails );
dump()
The dump
function dumps the given variables:
dump ($ value );
dump ($ value1 , $ value2 , $ value3 , ... );
If you desire to end executing the script later on dumping the variables, utilise the dd
role instead.
encrypt()
The encrypt
function encrypts the given value. You may employ this function as an alternative to the Crypt
facade:
$undercover = encrypt ( ' my-secret-value ' );
env()
The env
function retrieves the value of an surroundings variable or returns a default value:
$env = env ( ' APP_ENV ' );
$env = env ( ' APP_ENV ' , ' production ' );
{note} If you execute the
config:cache
command during your deployment procedure, you should be sure that you are only calling theenv
function from inside your configuration files. Once the configuration has been buried, the.env
file will not be loaded and all calls to theenv
function will renderzero
.
event()
The outcome
function dispatches the given event to its listeners:
result ( new UserRegistered ($ user ));
filled()
The filled
part determines whether the given value is not "blank":
filled ( 0 );
filled ( truthful );
filled ( imitation );
// truthful
filled ( '' );
filled ( ' ' );
filled ( null );
filled ( collect ());
// false
For the changed of filled
, come across the blank
method.
info()
The info
function will write information to your application's log:
info ( ' Some helpful information! ' );
An assortment of contextual information may likewise be passed to the role:
info ( ' User login attempt failed. ' , [ ' id ' => $ user ->id ]);
logger()
The logger
function can be used to write a debug
level message to the log:
logger ( ' Debug message ' );
An assortment of contextual data may besides be passed to the function:
logger ( ' User has logged in. ' , [ ' id ' => $ user ->id ]);
A logger case will exist returned if no value is passed to the role:
logger () -> mistake ( ' You are not allowed here. ' );
method_field()
The method_field
role generates an HTML subconscious
input field containing the spoofed value of the form'due south HTTP verb. For example, using Blade syntax:
< form method = " Mail service " >
{{ method_field ( ' DELETE ' ) }}
< / form >
now()
The at present
role creates a new Illuminate\Support\Carbon
instance for the current fourth dimension:
$now = now ();
one-time()
The old
office retrieves an old input value flashed into the session:
$value = old ( ' value ' );
$value = quondam ( ' value ' , ' default ' );
optional()
The optional
function accepts whatever argument and allows you to access properties or call methods on that object. If the given object is goose egg
, properties and methods volition return goose egg
instead of causing an error:
return optional ($ user ->accost ) ->street ;
{ !! erstwhile ( ' name ' , optional ($ user ) ->name ) !! }
The optional
part also accepts a closure as its second statement. The closure will be invoked if the value provided as the first argument is not zippo:
return optional ( User :: detect ($ id ), function ( $ user ) {
return $ user ->name ;
});
policy()
The policy
method retrieves a policy instance for a given form:
$policy = policy ( App \ Models \ User :: class );
redirect()
The redirect
function returns a redirect HTTP response, or returns the redirector instance if chosen with no arguments:
return redirect ($ to = null , $ status = 302 , $ headers = [], $ https = null );
return redirect ( ' /dwelling ' );
return redirect () -> route ( ' road.proper noun ' );
report()
The study
function will written report an exception using your exception handler:
report ($ eastward );
The study
function also accepts a string as an argument. When a string is given to the function, the office will create an exception with the given string every bit its message:
report ( ' Something went incorrect. ' );
request()
The request
role returns the current request case or obtains an input field's value from the electric current request:
$asking = request ();
$value = request ( ' fundamental ' , $ default );
rescue()
The rescue
function executes the given closure and catches any exceptions that occur during its execution. All exceptions that are defenseless will exist sent to your exception handler; however, the request will continue processing:
return rescue ( function () {
return $ this -> method ();
});
You lot may also pass a 2nd argument to the rescue
function. This argument will be the "default" value that should exist returned if an exception occurs while executing the closure:
return rescue ( function () {
render $ this -> method ();
}, false );
render rescue ( function () {
return $ this -> method ();
}, office () {
return $ this -> failure ();
});
resolve()
The resolve
function resolves a given class or interface proper noun to an case using the service container:
$api = resolve ( ' HelpSpot\API ' );
response()
The response
function creates a response instance or obtains an example of the response manufacturing plant:
return response ( ' Hello World ' , 200 , $ headers );
render 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 non throw an exception, its render value will be returned. If the callback throws an exception, information technology will automatically be retried. If the maximum attempt count is exceeded, the exception will exist thrown:
return retry ( v , role () {
// Attempt 5 times while resting 100ms between attempts...
}, 100 );
If you lot would similar to manually calculate the number of milliseconds to sleep between attempts, you may pass a closure as the tertiary statement to the retry
function:
return retry ( v , function () {
// ...
}, function ( $ endeavour ) {
return $ attempt * 100 ;
});
For convenience, you may provide an array every bit the first statement to the retry
function. This array will be used to make up one's mind how many milliseconds to sleep between subsequent attempts:
return retry ([ 100 , 200 ] function () {
// Sleep for 100ms on get-go retry, 200ms on second retry...
});
To only retry under specific conditions, you may pass a closure as the fourth argument to the retry
function:
return retry ( five , function () {
// ...
}, 100 , role ( $ exception ) {
return $ exception instanceof RetryException ;
});
session()
The session
function may be used to get or set up session values:
$value = session ( ' key ' );
You may set values past passing an assortment of primal / value pairs to the office:
session ([ ' chairs ' => 7 , ' instruments ' => 3 ]);
The session shop will be returned if no value is passed to the function:
$value = session () -> go ( ' key ' );
session () -> put ( ' cardinal ' , $value );
tap()
The tap
role accepts two arguments: an arbitrary $value
and a closure. The $value
will exist passed to the closure and and so be returned by the tap
office. The render value of the closure is irrelevant:
$user = tap ( User :: first (), function ( $ user ) {
$ user ->name = ' taylor ' ;
$ user -> save ();
});
If no closure is passed to the tap
office, you may call any method on the given $value
. The return value of the method you lot call will always be $value
, regardless of what the method really returns in its definition. For example, the Eloquent update
method typically returns an integer. Even so, we can force the method to return the model itself by chaining the update
method call through the tap
function:
$user = tap ($ user ) -> update ([
' name ' => $name ,
' e-mail ' => $email ,
]);
To add a tap
method to a form, y'all may add the Illuminate\Back up\Traits\Tappable
trait to the class. The tap
method of this trait accepts a Closure as its only argument. The object instance itself volition be passed to the Closure and and so be returned past the tap
method:
render $user -> tap ( part ( $user ) {
//
});
throw_if()
The throw_if
function throws the given exception if a given boolean expression evaluates to true
:
throw_if ( ! Auth :: user () -> isAdmin (), AuthorizationException :: class );
throw_if (
! Auth :: user () -> isAdmin (),
AuthorizationException :: course ,
' You are not allowed to admission this page. '
);
throw_unless()
The throw_unless
role throws the given exception if a given boolean expression evaluates to false
:
throw_unless ( Auth :: user () -> isAdmin (), AuthorizationException :: grade );
throw_unless (
Auth :: user () -> isAdmin (),
AuthorizationException :: course ,
' You are not allowed to admission this page. '
);
today()
The today
function creates a new Illuminate\Support\Carbon
instance for the current appointment:
$today = today ();
trait_uses_recursive()
The trait_uses_recursive
function returns all traits used by a trait:
$traits = trait_uses_recursive (\ Illuminate \ Notifications \ Notifiable :: course );
transform()
The transform
function executes a closure on a given value if the value is non bare and so returns the return value of the closure:
$callback = function ( $value ) {
return $value * ii ;
};
$result = transform ( 5 , $ callback );
// x
A default value or closure may be passed every bit the third argument to the function. This value will be returned if the given value is blank:
$consequence = transform ( null , $ callback , ' The value is blank ' );
// The value is blank
validator()
The validator
part creates a new validator example with the given arguments. You may use it as an alternative to the Validator
facade:
$validator = validator ($ information , $ rules , $ messages );
value()
The value
function returns the value information technology is given. However, if you lot pass a closure to the role, the closure volition be executed and its returned value will be returned:
$issue = value ( true );
// true
$result = value ( function () {
return imitation ;
});
// false
view()
The view
function retrieves a view instance:
return view ( ' auth.login ' );
with()
The with
function returns the value it is given. If a closure is passed as the second statement to the function, the closure will exist executed and its returned value will exist returned:
$callback = office ( $value ) {
return is_numeric ($ value ) ? $value * 2 : 0 ;
};
$issue = with ( 5 , $ callback );
// ten
$issue = with ( zip , $ callback );
// 0
$issue = with ( 5 , null );
// five
Source: https://laravel.com/docs/9.x/helpers
Posted by: lanegrosse.blogspot.com
0 Response to "How To Clean A String Of Characters So It Can Be Used In The Url Php"
Post a Comment