auxiliary function


brief introduction

Laravel comes with a series of PHP auxiliary functions, many of which are used by the framework itself. If you feel convenient, you can also use them in the code.

Method List

Arrays&Objects

Arr::add()

Arr::add Method to add the given key value pair to the array -- if the given key does not exist or the corresponding value is empty:

 use Illuminate\Support\Arr; $array = Arr::add(['name' => 'Desk'], 'price', 100); // ['name' => 'Desk', 'price' => 100] $array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100); // ['name' => 'Desk', 'price' => 100]

Arr::collapse()

Arr::collapse() Method to combine multiple arrays into one:

 use Illuminate\Support\Arr; $array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Arr::divide()

Arr::divide The method returns two arrays, one containing all the keys of the original array and the other containing all the values of the original array:

 use Illuminate\Support\Arr; [$keys, $values] = Arr::divide(['name' => 'Desk']); // $keys: ['name'] // $values: ['Desk']

Arr::dot()

Arr::dot Method Use the "." sign to convert a multidimensional array into a one-dimensional array:

 use Illuminate\Support\Arr; $array = ['products' => ['desk' => ['price' => 100]]]; $flattened = Arr::dot($array); // ['products.desk.price' => 100]

Arr::except()

Arr::except Method to remove the given key value pair from the array:

 use Illuminate\Support\Arr; $array = ['name' => 'Desk', 'price' => 100]; $filtered = Arr::except($array, ['price']); // ['name' => 'Desk']

Arr::first()

Arr::first Method returns the first element of the test array:

 use Illuminate\Support\Arr; $array = [100, 200, 300]; $first = Arr::first($array, function ($value, $key) { return $value >= 150; }); // 200

The default value can be passed to the method as the third parameter. If no value passes the test, the default value will be returned:

 use Illuminate\Support\Arr; $first = Arr::first($array, $callback, $default);

Arr::flatten()

Arr::flatten Method to convert a multidimensional array into a one-dimensional array:

 use Illuminate\Support\Arr; $array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]; $flattened = Arr::flatten($array); // ['Joe', 'PHP', 'Ruby']

Arr::forget()

Arr::forget Method uses the "." sign to remove the given key value pair from the nested array:

 use Illuminate\Support\Arr; $array = ['products' => ['desk' => ['price' => 100]]]; Arr::forget($array, 'products.desk'); // ['products' => []]

Arr::get()

Arr::get The method uses the "." sign to obtain a value from a nested array:

 use Illuminate\Support\Arr; $array = ['products' => ['desk' => ['price' => 100]]]; $price = Arr::get($array, 'products.desk.price'); // 100

Arr::get The method also receives a default value. If the specified key does not exist, it returns the default value:

 use Illuminate\Support\Arr; $discount = Arr::get($array, 'products.desk.discount', 0); // 0

Arr::has()

Arr::has Method uses "." to check whether the given data item exists in the array:

 use Illuminate\Support\Arr; $array = ['product' => ['name' => 'Desk', 'price' => 100]]; $contains = Arr::has($array, 'product.name'); // true $contains = Arr::has($array, ['product.price', 'product.discount']); // false

Arr::last()

Arr::last Method returns the last element of the filtered array:

 use Illuminate\Support\Arr; $array = [100, 200, 300, 110]; $last = Arr::last($array, function ($value, $key) { return $value >= 150; }); // 300

We can pass a default value as the third parameter to the method. If no value passes the truth test, the default value will be returned:

 use Illuminate\Support\Arr; $last = Arr::last($array, $callback, $default);

Arr::only()

Arr::only Method only returns the specified key value pair 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()

Arr::pluck Method returns the list of key value pairs corresponding to the given key from the array:

 use Illuminate\Support\Arr; $array = [ ['developer' => ['id' => 1, 'name' => 'Taylor']], ['developer' => ['id' => 2, 'name' => 'Abigail']], ]; $names = Arr::pluck($array, 'developer.name'); // ['Taylor', 'Abigail']

You can also specify the key to return results:

 use Illuminate\Support\Arr; $names = Arr::pluck($array, 'developer.name', 'developer.id'); // [1 => 'Taylor', 2 => 'Abigail']

Arr::prepend()

Arr::prepend Method to push the data item to the beginning of the array:

 use Illuminate\Support\Arr; $array = ['one', 'two', 'three', 'four']; $array = Arr::prepend($array, 'zero'); // ['zero', 'one', 'two', 'three', 'four']

If necessary, you can also specify the key for this value:

 use Illuminate\Support\Arr; $array = ['price' => 100]; $array = Arr::prepend($array, 'Desk', 'name'); // ['name' => 'Desk', 'price' => 100]

Arr::pull()

Arr::pull Method returns and removes key value pairs from an array:

 use Illuminate\Support\Arr; $array = ['name' => 'Desk', 'price' => 100]; $name = Arr::pull($array, 'name'); // $name: Desk // $array: ['price' => 100]

We can also pass the default value as the third parameter to the method, and return the value if the specified key does not exist:

 use Illuminate\Support\Arr; $value = Arr::pull($array, $key, $default);

Arr::random()

Arr::random Method returns a random value from an array:

 use Illuminate\Support\Arr; $array = [1, 2, 3, 4, 5]; $random = Arr::random($array); // 4 - (retrieved randomly)

You can also specify the number of returned data items as an optional second parameter. Note that providing this parameter will return an array, even if only one data item is returned:

 use Illuminate\Support\Arr; $items = Arr::random($array, 2); // [2, 5] - (retrieved randomly)

Arr::set()

Arr::set Method is used to set the value using the "." sign in a nested array:

 use Illuminate\Support\Arr; $array = ['products' => ['desk' => ['price' => 100]]]; Arr::set($array, 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 200]]]

Arr::sort()

Arr::sort Method sorts the array by value:

 use Illuminate\Support\Arr; $array = ['Desk', 'Table', 'Chair']; $sorted = Arr::sort($array); // ['Chair', 'Desk', 'Table']

You can also sort the array by the result of a given closure:

 use Illuminate\Support\Arr; $array = [ ['name' => 'Desk'], ['name' => 'Table'], ['name' => 'Chair'], ]; $sorted = array_values(Arr::sort($array, function ($value) { return $value['name']; })); /* [ ['name' => 'Chair'], ['name' => 'Desk'], ['name' => 'Table'], ] */

Arr::sortRecursive()

Arr::sortRecursive Method use sort Function pair index array ksort Function to sort the associative array recursively:

 use Illuminate\Support\Arr; $array = [ ['Roman', 'Taylor', 'Li'], ['PHP', 'Ruby', 'JavaScript'], ['one' => 1, 'two' => 2, 'three' => 3], ]; $sorted = Arr::sortRecursive($array); /* [ ['JavaScript', 'PHP', 'Ruby'], ['one' => 1, 'three' => 3, 'two' => 2], ['Li', 'Roman', 'Taylor'], ] */

Arr::where()

Arr::where Method filters the array using the given closure:

 use Illuminate\Support\Arr; $array = [100, '200', 300, '400', 500]; $filtered = Arr::where($array, function ($value, $key) { return is_string($value); }); // [1 => '200', 3 => '400']

Arr::wrap()

Arr::wrap Method wraps the given value into an array. If the given value is already an array, it remains unchanged:

 use Illuminate\Support\Arr; $string = 'Laravel'; $array = Arr::wrap($string); // ['Laravel']

If the given value is empty, an empty array is returned:

 use Illuminate\Support\Arr; $nothing = null; $array = Arr::wrap($nothing); // []

data_fill()

data_fill The function uses the "." sign to set the missing value in a nested array or object:

 $data = ['products' => ['desk' => ['price' => 100]]]; data_fill($data, 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 100]]] data_fill($data, 'products.desk.discount', 10); // ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]

The function also receives the "*" sign as a wildcard and fills in the corresponding target:

 $data = [ 'products' => [ ['name' => 'Desk 1', 'price' => 100], ['name' => 'Desk 2'], ], ]; data_fill($data, 'products.*.price', 200); /* [ 'products' => [ ['name' => 'Desk 1', 'price' => 100], ['name' => 'Desk 2', 'price' => 200], ], ] */

data_get()

data_get The function uses the "." sign to obtain a value from a nested array or object:

 $data = ['products' => ['desk' => ['price' => 100]]]; $price = data_get($data, 'products.desk.price'); // 100

data_get The function also receives a default value so that if the specified key does not exist, it returns:

 $discount = data_get($data, 'products.desk.discount', 0); // 0

data_set()

data_set The function uses the "." symbol to set the value of a nested array or object:

 $data = ['products' => ['desk' => ['price' => 100]]]; data_set($data, 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 200]]]

The function also receives wildcards and sets the corresponding target value:

 $data = [ 'products' => [ ['name' => 'Desk 1', 'price' => 100], ['name' => 'Desk 2', 'price' => 150], ], ]; data_set($data, 'products.*.price', 200); /* [ 'products' => [ ['name' => 'Desk 1', 'price' => 200], ['name' => 'Desk 2', 'price' => 200], ], ] */

By default, any existing values will be overwritten. If you want to set only nonexistent values, you can pass false As the third parameter:

 $data = ['products' => ['desk' => ['price' => 100]]]; data_set($data, 'products.desk.price', 200, false); // ['products' => ['desk' => ['price' => 100]]]

head()

head The function simply returns the first element of the given array:

 $array = [100, 200, 300]; $first = head($array); // 100

last()

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

 $array = [100, 200, 300]; $last = last($array); // 300

Path function

app_path()

app_path Function return app The absolute path of the directory. You can also use app_path Function is relative to app The given file generation absolute path of the directory:

 $path = app_path(); $path = app_path('Http/Controllers/Controller.php');

base_path()

base_path The function returns the absolute path of the project root directory. You can also use the base_path The function generates an absolute path for a given file relative to the application root directory:

 $path = base_path(); $path = base_path('vendor/bin');

config_path()

config_path Function returns the application configuration directory config The absolute path of, you can also use config_path The function generates a full path for the given file in the application configuration directory:

 $path = config_path(); $path = config_path('app.php');

database_path()

database_path Function returns the application database directory database The full path of the. You can also use the database_path The function generates a full path for the given file in the database directory:

 $path = database_path(); $path = database_path('factories/UserFactory.php');

mix()

mix Function return Mix file with version number route:

 $path = mix('css/app.css');

public_path()

public_path Function return public The absolute path of the directory. You can also use the public_path The function generates a full path for the given file in the public directory:

 $path = public_path(); $path = public_path('css/app.css');

resource_path()

resource_path Function return resources The absolute path of the directory. You can also use the resources Function in resources Generate a full path for the given file in the directory:

 $path = resource_path(); $path = resource_path('sass/app.scss');

storage_path()

storage_path Function return storage The absolute path of the directory. You can also use the storage_path Function in storage Generate a full path for the given file in the directory:

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

String function

__()

__ The function will use Localized files Translate the given translation string or key:

 echo __('Welcome to our application'); echo __('messages.welcome');

If the given translation string or key does not exist, __ The function will return the given value. So, use the above example, if the translation key does not exist __ The function will return messages.welcome

class_basename()

class_basename Return the class name of the given class after removing the namespace:

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

e()

e Function runs on the given string htmlentities double_encode Option set to false ):

 echo e('<html>foo</html>'); // <html>foo</html>

preg_replace_array()

preg_replace_array The function replaces the given pattern in a string sequence with an array:

 $string = 'The event will take place between :start and :end'; $replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string); // The event will take place between 8:30 and 9:00

Str::after()

Str::after Method returns all contents after the given value in the string:

 use Illuminate\Support\Str; $slice = Str::after('This is my name', 'This is'); // ' my name'

Str::before()

Str::before Method returns all contents before the given value in the string:

 use Illuminate\Support\Str; $slice = Str::before('This is my name', 'my name'); // 'This is '

Str::camel()

Str::camel Converts the given string to a shape like camelCase Hump style:

 use Illuminate\Support\Str; $converted = Str::camel('foo_bar'); // fooBar

Str::contains()

Str::contains Method to determine whether a given string contains a given value (case sensitive):

 use Illuminate\Support\Str; $contains = Str::contains('This is my name', 'my'); // true

You can also pass array values to determine whether a given string contains any value in the array:

 use Illuminate\Support\Str; $contains = Str::contains('This is my name', ['my', 'foo']); // true

Str::endsWith()

Str::endsWith Method is used to determine whether a string ends with a given value:

 use Illuminate\Support\Str; $result = Str::endsWith('This is my name', 'name'); // true

Str::finish()

Str::finish Method to add a single instance of the given value to the end of the string -- if the original string does not end with the given value:

 use Illuminate\Support\Str; $adjusted = Str::finish('this/string', '/'); // this/string/ $adjusted = Str::finish('this/string/', '/'); // this/string/

Str::is()

Str::is Method to determine whether a given string matches a given pattern. Asterisks can be used to indicate wildcards:

 use Illuminate\Support\Str; $matches = Str::is('foo*', 'foobar'); // true $matches = Str::is('baz*', 'foobar'); // false

Str::kebab()

Str::kebeb Method to convert the given string into a kebab case style string:

 use Illuminate\Support\Str; $converted = Str::kebab('fooBar'); // foo-bar

Str::limit()

Str::limit Method to truncate a string with the specified length:

 use Illuminate\Support\Str; $truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20); // The quick brown fox...

You can also pass a third parameter to change the character at the end of the string:

 use Illuminate\Support\Str; $truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)'); // The quick brown fox (...)

Str::orderedUuid()

Str::orderedUuid Method will generate a "timestamp first" UUID for more efficient storage in database index fields:

 use Illuminate\Support\Str; return (string) Str::orderedUuid();

Str::plural()

Str::plural Method to convert a string into a complex form. This function currently only supports English:

 use Illuminate\Support\Str; $plural = Str::plural('car'); // cars $plural = Str::plural('child'); // children

You can also pass integer data as the second parameter to the function to obtain the singular or plural form of the string:

 use Illuminate\Support\Str; $plural = Str::plural('child', 2); // children $plural = Str::plural('child', 1); // child

Str::random()

Str::random Method generates a random string by specifying the length. This function uses PHP's random_bytes Function:

 use Illuminate\Support\Str; $random = Str::random(40);

Str::replaceArray()

Str::replaceArray Method uses an array to replace the given value in a string sequence:

 use Illuminate\Support\Str; $string = 'The event will take place between ?  and ?'; $replaced = Str::replaceArray('?', ['8:30', '9:00'], $string); // The event will take place between 8:30 and 9:00

Str::replaceFirst()

Str::replaceFirst Method replaces the first occurrence of the value in the string:

 use Illuminate\Support\Str; $replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog'); // a quick brown fox jumps over the lazy dog

Str::replaceLast()

Str::replaceLast Method replaces the last occurrence of the value in the string:

 use Illuminate\Support\Str; $replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog'); // the quick brown fox jumps over a lazy dog

Str::singular()

Str::singular Method to convert a string to a singular form. At present, this function only supports English:

 use Illuminate\Support\Str; $singular = Str::singular('cars'); // car $singular = Str::singular('children'); // child

Str::slug()

Str::slug Method to generate a URL friendly format for the given string:

 use Illuminate\Support\Str; $slug = Str::slug('Laravel 5 Framework', '-'); // laravel-5-framework

Str::snake()

Str::snake Method to convert the given string to a shape such as snake_case Format string:

 use Illuminate\Support\Str; $converted = Str::snake('fooBar'); // foo_bar

Str::start()

If the string does not start with the given value Str::start Method will add the given value to the front of the string:

 use Illuminate\Support\Str; $adjusted = Str::start('this/string', '/'); // /this/string $adjusted = Str::start('/this/string', '/'); // /this/string

Str::startsWith()

Str::startsWith Method is used to determine whether the incoming string starts with the given value:

 use Illuminate\Support\Str; $result = Str::startsWith('This is my name', 'This'); // true

Str::studly()

Str::studly Method to convert the given string to a form such as StudlyCase The format of the initial letter of the word:

 use Illuminate\Support\Str; $converted = Str::studly('foo_bar'); // FooBar

Str::title()

Str::title Method to convert a string to a form such as Title Case Format of:

 use Illuminate\Support\Str; $converted = Str::title('a nice title uses the correct case'); // A Nice Title Uses The Correct Case

Str::uuid()

Str::uuid Method to generate a UUID (version 4):

 use Illuminate\Support\Str; return (string) Str::uuid();

trans()

trans Function Usage Local file Translate the given translation key:

 echo trans('messages.welcome');

If the specified translation key does not exist, trans The function will return the given key. So, take the above example, if the translation key does not exist, trans The function will return messages.welcome

trans_choice()

trans_choice Function translation Given translation key with inflection point:

 echo trans_choice('messages.notifications', $unreadCount);

If the specified translation key does not exist, trans_choice The function returns it. So, take the above example, if the specified translation key does not exist trans_choice The function will return messages.notifications

URL function

action()

action The function generates a URL for a given controller action. You do not need to pass a complete namespace to the controller App\Http\Controllers The class name of can be:

 $url = action(' HomeController@index '); $url = action([HomeController::class, 'index']);

If this method receives routing parameters, you can pass them in as the second parameter:

 $url = action(' UserController@profile ', ['id' => 1]);

asset()

asset The function uses the current request scheme (HTTP or HTTPS) to generate a URL for front-end resources:

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

You can use the .env Set in file ASSET_URL Variable to configure the resource URL host name. This function is useful if you host resources in a third-party service such as Amazon S3:

 // ASSET_URL= http://example.com/assets $url = asset('img/photo.jpg'); //  http://example.com/assets/img/photo.jpg

secure_asset()

secure_asset The function uses HTTPS to generate a URL for front-end resources:

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

route()

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

 $url = route('routeName');

If the route receives parameters, you can pass them in as the second parameter:

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

By default, route The function generates an absolute URL. If you want to generate a relative URL, you can pass false As the third parameter:

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

secure_url

secure_url The function generates a complete HTTPS URL for the given path:

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

url()

url The function generates a full URL for the given path:

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

If no path is provided, it will return Illuminate\Routing\UrlGenerator example:

 echo url()->current(); echo url()->full(); echo url()->previous();

Other functions

abort()

abort The function will throw a Exception handler Rendered HTTP exception

 abort(403);

You can also provide exception response text and custom response headers:

 abort(403, 'Unauthorized.', $ headers);

abort_if()

abort_if Function in the given Boolean expression is true An HTTP exception was thrown when:

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

and abort Similarly, you can also pass the exception response text as the third parameter and the custom response header array as the fourth parameter.

abort_unless()

abort_unless Function in the given Boolean expression is false An HTTP exception was thrown when:

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

and abort Similarly, you can also pass the exception response text as the third parameter and the custom response header array as the fourth parameter.

app()

app Function return Service Container example:

 $container = app();

You can also pass the class or interface name to resolve it from the container:

 $api = app('HelpSpot\API');

auth()

auth The function returns a Authenticator Example, you can use it instead for convenience Auth Facade:

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

If necessary, you can also specify the guard instance you want to use:

 $user = auth('admin')->user();

back()

back Function generation HTTP Redirect Response Go to the user's previous access page:

 return back($status = 302, $headers = [], $fallback = false); return back();

bcrypt()

bcrypt The function uses Bcrypt to perform Hash , you can use it instead Hash Facade:

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

blank()

blank The function returns whether the given value is null:

 blank(''); blank('   '); blank(null); blank(collect()); // true blank(0); blank(true); blank(false); // false

And blank In contrast filled Function.

broadcast()

broadcast function radio broadcast given event To listener:

 broadcast(new UserRegistered($user));

cache()

cache Function can be used from cache If the given key does not exist in the cache, the optional default value will be returned:

 $value = cache('key'); $value = cache('key', 'default');

You can add data items to the cache by passing array key value pairs to functions. Delivery cache validity period (seconds) is also required:

 cache(['key' => 'value'], 5); cache(['key' => 'value'], now()->addSeconds(10));

class_uses_recursive()

class_uses_recursive All traits used by a function class, including those used by subclasses:

 $traits = class_uses_recursive(App\User::class);

collect()

collect The function will create a aggregate

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

config()

config Function acquisition to configure The value of the variable can be configured by using "." Number access, including the file name and the options you want to access. If the configuration option does not exist, the default value will be specified and returned:

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

auxiliary function config It can also be used to set configuration variable values for arrays by passing key values at runtime:

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

cookie()

cookie Function can be used to create a new Cookie example:

 $cookie = cookie('name', 'value', $minutes);

csrf_field()

csrf_field The function generates an HTML hidden field containing the CSRF token value. For example, use the Blade syntax Examples are as follows:

 {{ csrf_field() }}

csrf_token()

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

 $token = csrf_token();

dd()

dd The function outputs the given variable value and terminates script execution:

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

If you don't want to stop the script, you can use dump Function.

decrypt()

decrypt Function uses Laravel Encryptor Decrypt the given value:

 $decrypted = decrypt($encrypted_value);

dispatch()

dispatch The function pushes a new task to Laravel Task Queue

 dispatch(new App\Jobs\SendEmails);

dispatch_now()

dispatch_now The function will immediately run the given task and return handle Method processing results:

 $result = dispatch_now(new App\Jobs\SendEmails);

dump()

dump The function prints the given variable:

 dump($value); dump($value1, $value2, $value3, ...);

If you want to terminate script execution after printing variables, you can use dd Function instead.

Note: You can use Artisan's dump-server Command to block all dump Call and display them in the console window.

encrypt()

encrypt Function uses Laravel Encryptor Encrypt the given string:

 $encrypted = encrypt($unencrypted_value);

env()

env Function acquisition environment variable Value or return the default value:

 $env = env('APP_ENV'); //If the variable does not exist, return the default value $env = env('APP_ENV', 'production');

Note: If you execute config:cache Command, you need to ensure that only the env , once the configuration is cached, .env The file will not be loaded, so all pairs of env All function calls will return null

event()

event Function distribution given event To the corresponding listener:

 event(new UserRegistered($user));

factory()

factory Function to create a model factory builder for a given class, name, and quantity, which can be used to test or Data filling

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

filled()

filled The function will return whether the given value is not empty:

 filled(0); filled(true); filled(false); // true filled(''); filled('   '); filled(null); filled(collect()); // false

And filled In contrast blank Function.

info()

info The function will record information to Log system

 info('Some helpful information!');

You can also pass the context data array to this function:

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

logger()

logger Functions can be used to record debug Log messages at level:

 logger('Debug message');

Similarly, you can also pass the context data array to this function:

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

If no value is passed into this function, it will return journal example:

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

method_field()

method_field Function to generate HTML containing HTTP request methods hidden Form fields, such as:

 <form method="POST"> {{ method_field('DELETE') }} </form>

now()

now Function to create a new Illuminate\Support\Carbon example:

 $now = now();

old()

old Function acquisition is stored in a one-time session Last input Value of:

 $value = old('value'); $value = old('value', 'default');

optional()

optional The function takes arbitrary parameters and allows you to access properties on an object or call its methods. If the given object is empty, the property or method call returns null Instead of errors:

 return optional($user->address)->street; {!! old('name', optional($user)->name) !!}

optional The function can also receive a closure as the second parameter. The closure will be called when the first parameter value is not empty:

 return optional(User::find($id), function ($user) { return new DummyUser; });

policy()

policy Function to obtain the corresponding for the given model class strategy example:

 $policy = policy(App\User::class);

redirect()

redirect Function return HTTP Redirect Response , if there is no parameter, return the redirector example:

 return redirect($to = null, $status = 302, $headers = [], $secure = null); return redirect('/home'); return redirect()->route('route.name');

report()

report The function will use Exception handler Of report Method report exception:

 report($e);

request()

request Function returns the current request Instance or obtain an input item:

 $request = request(); $value = request('key', $default);

rescue()

rescue Functions can execute a given closure and catch all exceptions during execution. These captured exceptions will be sent to the exception handler report Method, however, the request continues to execute:

 return rescue(function () { return $this->method(); });

You can also pass the second parameter to rescue Function, as the default value returned in case of exception in executing the closure:

 return rescue(function () { return $this->method(); }, false); return rescue(function () { return $this->method(); }, function () { return $this->failure(); });

resolve()

resolve Function Usage Service Container Resolve the given class or interface name to the corresponding binding instance:

 $api = resolve('HelpSpot\API');

response()

response Function to create a response Instance or get the response factory instance:

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

retry()

retry The function attempts to execute the given callback until the maximum number of executions is reached. If the callback does not throw an exception, it will return the corresponding return value. If the callback throws an exception, it will automatically retry. If the maximum execution times are exceeded, an exception will be thrown:

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

session()

session Function can be used to get/set Session Value:

 $value = session('key');

You can set the session value by passing the key value pair array to this function:

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

If no parameter is passed to session The function returns the Session storage object instance:

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

tap()

tap The function takes two parameters: arbitrary $value And a closure. $value Will be passed to the closure and passed through tap Function returns. The return value of the closure is not related to the return value of the function:

 $user = tap(User::first(), function ($user) { $user->name = 'taylor'; $user->save(); });

If no closure is passed in to tap Function, then you can call the given $value For any of the above methods, the return value of the calling method is always $value , regardless of the return value defined in the method. For example, Eloquent update The method usually returns an integer, but we can force the method to return the model itself through the tap function:

 $user = tap($user)->update([ 'name' => $name, 'email' => $email, ]);

throw_if()

throw_if The function will true Throw the given exception in the case of

 throw_if(!  Auth::user()->isAdmin(),  AuthorizationException::class); throw_if( !  Auth::user()->isAdmin(), AuthorizationException::class, 'You are not allowed to access this page' );

throw_unless()

throw_unless The function will false Throw the given exception in the case of

 throw_unless(Auth::user()->isAdmin(),  AuthorizationException::class); throw_unless( Auth::user()->isAdmin(), AuthorizationException::class, 'You are not allowed to access this page' );

today()

today The function will create a new Illuminate\Support\Carbon example:

 $today = today();

trait_uses_recursive()

trait_uses_recursive The function returns all traits used by a trait:

 $traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);

transform()

transform The function will execute the closure and return the closure result when the given value is not empty:

 $callback = function ($value) { return $value * 2; }; $result = transform(5, $callback); // 10

The default value or closure can be passed to the function in the form of the third parameter. The default value is returned when the given value is empty:

 $result = transform(null, $callback, 'The value is blank'); // The value is blank

validator()

validator Function creates a new Validator Instance, which can be used instead of Validator Facade:

 $validator = validator($data, $rules, $messages);

value()

value The function returns the given value. However, if you pass a closure to the function, the closure will be executed and the execution result will be returned:

 $result = value(true); // true $result = value(function () { return false; }); // false

view()

view Function to get a view example:

 return view('auth.login');

with()

with The function returns the given value. If the second parameter is a closure, it returns the closure execution result:

 $callback = function ($value) { return (is_numeric($value)) ? $ value * 2 : 0; }; $result = with(5, $callback); // 10 $result = with(null, $callback); // 0 $result = with(5, null); // 5

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: file store

>>Next: mail