Helper function


##Auxiliary function

    Introduction
  • Available methods

##Introduction
Laravel contains a variety of "global" PHP auxiliary functions, and the framework itself also uses a large number of these functional functions; if you find it convenient, you can use it in your application These functions

Available methods

数组 & 对象

路径

字符串

URLs

Other

##Method List

##Array & Object

##Arr::add()

If the given key does not exist in the array, then the Arr::add

function will add the given key/value pair Add to the array:

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

##Arr::collapse()

Arr::collapse Function combines multiple arrays into one array:

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

Arr::divide()

Arr::divide The function returns a two-dimensional array, one value contains the key of the original array, and the other value contains The value of the original array:

use Illuminate\Support\Arr;
[$keys, $values] = Arr::divide(['name' => 'Desk']);
// $keys: ['name']  多维数组中的第0个值
// $values: ['Desk']  多维数组中的第1个值

##Arr::dot()

Arr::dot The function tiles all the keys in the multi-dimensional array into a one-dimensional array. The new array uses the "." symbol to indicate the hierarchical inclusion relationship:

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

Arr::except()

Arr::except Function removes the given key/value from the array Right:

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

Arr::first()

Arr: :first The function returns the first element in the array that passes the specified test:

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

Pass the default value as the third parameter to this method. If no value in the array passes the test, the default value is returned. :

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

Arr::flatten()

##Arr:: The flatten

function flattens the values ​​of the array in the multi-dimensional 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

The function uses the "." notation to remove the given key/value pair from a deeply nested array:

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

Arr::get()

Arr::get

Function usage The "." symbol retrieves a value from a deeply nested array based on the specified key:

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

Arr::get

The function also accepts a default value and will return if the specific key is not found. Default value:

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

##Arr::has()

Arr ::has

The function uses the "." symbol to find whether one or more specified keys exist 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

The function returns the last element in the array that passes the specified test:

use Illuminate\Support\Arr;
$array = [100, 200, 300, 110];
$last = Arr::last($array, function ($value, $key) {  
  return $value >= 150;
 });
// 300
Replaces the default value Passed as the third argument to this method, if no value passes the specified test, this default value is returned:
use Illuminate\Support\Arr;
$last = Arr::last($array, $callback, $default);

# #Arr::only()

Arr::only The function returns only the key/value pairs specified in 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 Function retrieves the given from an array All values ​​of key:

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 of the obtained result:

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

Arr::prepend()

Arr::prepend The function inserts a value into 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 If required, you can specify the key where you insert the value:

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

##Arr::pull()

Arr::pull The function returns the value of the specified key from the array and deletes this key/value pair:

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

The default value can be passed to this method as the third parameter , if the key does not exist, the value is returned:

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

##Arr::random()

Arr::random

The function returns a random value from the array:

use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 4 - (随机检索)
You can also pass the number of return values ​​to this method as the optional second parameter , please note that providing this parameter will return an array, even if you only need one item:

use Illuminate\Support\Arr;
$items = Arr::random($array, 2);
// [2, 5] - (随机检索)

##Arr: :set()

Arr::set

The function uses the "." symbol to set the value of the specified key in a multi-dimensional 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

The function sorts the array based on its value. Sorting:

use Illuminate\Support\Arr;$array = ['Desk', 'Table', 'Chair'];
$sorted = Arr::sort($array);
// ['Chair', 'Desk', 'Table']
You can also sort the array based on the results returned by 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

Function uses the

sort function to recursively sort an array:

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

function is used to The result filter array returned by the fixed 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 The function turns the given value into an array. If the given value is already an array, it will not be changed:

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

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

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

#data_fill()

data_fill The function uses the "." symbol to set default values ​​​​in multi-dimensional arrays or objects:
$data = ['products' => ['desk' => ['price' => 100]]];
data_fill($data, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 100]]]
data_fill($data, 'products.desk.discount', 10);
// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]

This function also accepts the asterisk "*" as a wildcard character, and the corresponding fill 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 "." symbol to retrieve values ​​from a multidimensional array or object

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

data_get The function can also receive a default value. If the specified key cannot be found, the default value is returned:

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

This function also accepts "*" as a wildcard character, which can match any key of an array or object. :

$data = [ 
   'product-one' => ['name' => 'Desk 1', 'price' => 100],    
   'product-two' => ['name' => 'Desk 2', 'price' => 150],
 ];
data_get($data, '*.name');
   // ['Desk 1', 'Desk 2'];

data_set()

data_set Function usage The "." symbol sets a value in a multidimensional array or object:

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

This function can also accept the "*" wildcard character, and accordingly sets the value on the specified key:

$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 , all existing values ​​will be overwritten. If you only wish to set non-existing values, you can select false as the fourth parameter passed to the method:

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

head()

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

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

##last()

last Function returns the given array The last element in:

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

path

app_path()

app_path The function returns the full path of the app directory. You can also use the app_path function to set the full path to the application app directory:

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

base_path()

base_path The function returns the full path to the project root directory. You can also use the base_path function to set the full path to the project root directory:

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

config_path( )

config_path The function returns the full path of the config directory. You can also use the config_path function to set the full path to a given file in the application's config directory:

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

database_path()

database_path The function returns the full path of the database directory. You can also use the database_path function to set the full path to a given file in the database directory:

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

mix()

mix The function returns the path to the versioned Mix file:

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

public_path()

public_path The function returns the full path of the public directory. You can also use the public_path function to generate the full path to a given file in the public directory:

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

resource_path()

resource_path The function returns the full path of the resources directory. You can also use the resource_path function to generate the full path to a given file in a resource file

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

storage_path()

storage_path The function returns the full path of the storage directory. You can also use the storage_path function to set the full path to the specified file in the storage directory:

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

String

##__()

__ function uses your Localize the file to translate the given translation string or translation key:

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

If the specified translation string or translation key does not exist, the

__ function will return the given value. So, according to the above example, if the translation key messages.welcome does not exist, the __ function will return it directly.

##Str::camel()

The

Str::camel

method converts the given string to camelCase:Str::camel
The function converts the given string "snake style" into camelCase CamelCase":

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

##class_basename()

class_basename

The function returns the class name of the specified class with the namespace deleted:

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

e()

e

The function changes the

double_encode option value with the default value of true to false to run PHP of htmlspecialchars Function:

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

##Str::endsWith()

Str::endsWith The function determines whether the specified string ends with the given value:

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

Str::kebab()

Str::kebab The function converts the given "camel case" string into

kebab-case

"Short horizontal" string:

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

preg_replace_array()

preg_replace_array Function replaces a given pattern in a string using array order:

$string = 'The event will take place between :start and :end';
$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);
//  活动将在 8:30 至 9:00 之间进行

Str::snake()

Str::snake The function converts the given string to snake_case「Snake pose」:

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

##Str::startsWith()

Str::startsWith The function determines whether the beginning of the given string is the specified value:

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

Str::after()

Str::after The function returns everything after the specified value in the string:

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

##Str::before()

Str::before

Function return Everything before the specified value in the string:

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

##Str::contains()

Str::contains

Function determines whether the given string contains the given value (case sensitive):

use Illuminate\Support\Str;
$contains = Str::contains('This is my name', 'my');
// true
You can also pass an array of values ​​to Determine whether the string contains any values:
use Illuminate\Support\Str;
$contains = Str::contains('This is my name', ['my', 'foo']);
// true

##Str::finish()

Str::finish The function returns the given string ending with the given value (if it does not already 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 The function determines whether the given string matches the given string certain pattern. The asterisk * can be used to represent wildcards:

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

##Str::limit()

Str::limit Function truncates the given string by the given 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 string that will be appended to the end :

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

Str::orderedUuid()

The

Str: The :orderedUuid method efficiently generates a "first time" UUID that can be stored in an indexed database column:
use Illuminate\Support\Str;
return (string) Str::orderedUuid();

Str::plural()

Str::plural Function converts a string to plural form. This function currently only supports English:
use Illuminate\Support\Str;
$plural = Str::plural('car');
// cars
$plural = Str::plural('child');
// children

You can provide an integer as the second parameter of the function to retrieve the singular or plural form of the string:

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

Str::random()

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

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

##Str::replaceArray()

Str::replaceArray Function replaces a given value in a string using array order:

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 Function replaces the first occurrence of a given value in a string:

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

##Str::replaceLast()

Str::replaceLast

Function replaces the last occurrence of a given value in a string:

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

##Str::singular()

Str::singular

Function converts a string to singular form. This function currently only supports English:

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

##Str::slug()

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

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

Str::start()

Str::start Function adds the given value to the beginning of the given string (if the string is not already at the given Starting from a fixed value):

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

##Str::studly()

Str::studly The function converts the given string into "variant camel case naming":
use Illuminate\Support\Str;
$converted = Str::studly('foo_bar');
// FooBar

Str::title()

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

trans()

trans function converts the given translation secret using your local file Key:
echo trans('messages.welcome');

If the specified translation key does not exist, the

trans method will simply return the given key. So, in the above example, if the translation key does not exist, the trans

method will return

messages.welcome.

trans_choice()

trans_choice The function translates the given translation key according to the morphological changes:

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

If the specified translation key If not, the trans_choice method will simply return the given key. So, following the example above, if the translation key does not exist, the trans_choice method will return messages.notifications.

##Str::uuid()

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

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

##URLs

action()

action

The function generates a URL for the specified controller action. You don't need to pass the full controller namespace. Just pass the controller class name relative to the App\Http\Controllers namespace:

$url = action('HomeController@index');
$url = action([HomeController::class, 'index']);
If the method accepts route parameters, you can pass them as the second parameter of the method:

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

asset()

asset

The function uses the current The protocol of the request (HTTP or HTTPS) generates the URL for the resource file:

$url = asset('img/photo.jpg');
You can configure the asset URL by setting the

ASSET_URL

variable in the .env file host. This is useful if you are hosting your assets on an external service like 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 the HTTPS protocol to generate a URL for the resource file:

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

route()

route

The function generates a URL for the given named route:

$url = route('routeName');
If the route accepts parameters, they can be passed as methods The second parameter passed:

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

By default, the

route

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 standard HTTPS URL for the given path:

$url = secure_url('user/profile');
$url = secure_url('user/profile', [1]);

url()

url

Function generates the fully qualified URL for the given path:

$url = url('user/profile');
$url = url('user/profile', [1]);
If not provided path, then return

Illuminate\Routing\UrlGenerator

Instance:

$current = url()->current();
$full = url()->full();
$previous = url()->previous();

##Others

abort()

##abort The function throws an HTTP exception rendered by the exception handler:

abort(403);

You can also provide additional responses Text and custom response headers:

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

##abort_if()

if given A certain Boolean expression evaluates to

true

, and the abort_if function will throw an HTTP exception:

abort_if(! Auth::user()->isAdmin(), 403);
is the same as the

abort

method, you You can also provide the exception's response text as the third parameter, and provide custom response header data as the fourth parameter.

##abort_unless()

If the given boolean expression evaluates to false

,

abort_unless function will throw an HTTP exception:

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

method, you can also provide the exception response text as the first Three parameters, and provide a custom response header array as the fourth parameter.

##app()

app The function returns the service container Example:

$container = app();

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

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

auth()

auth The function returns an authentication instance. For convenience, you can use this instead of the

Auth

Facade:

$user = auth()->user();
If necessary, you can specify the authentication instance you want to access:
$user = auth('admin')->user();

back()

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

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

bcrypt()

##bcrypt Hash usage Bcrypt hashes the given value. You can use this instead of Hash

Facade:

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

##broadcast()

broadcast

The function will broadcast the given event to its listeners:
broadcast(new UserRegistered($user));

blank()

blank

Function determines whether the given value is empty:
blank('');
blank('   ');
blank(null);
blank(collect());
// true
blank(0);
blank(true);
blank(false);
// false
If you want to use the same function as

blank

For the opposite method, see the filled

method.

cache()

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

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

You can set the cache entry by adding an array of key-value pairs to the function. At the same time, you should also pass a valid number of minutes or cache duration to set the cache expiration time:

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

class_uses_recursive()

class_uses_recursive The function returns all traits used by a class, including traits used by all its parent classes:

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

collect()

collect function creates a collection instance based on the given value.

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

config()

config Function gets configuration The value of the variable. You can use "dot" syntax to access the configuration value, which includes the name of the file and the access option. If the accessed configuration option does not exist, you can specify a default value and return the default value:

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

You also Configuration variables can be set at runtime by passing an array of key/value pairs:

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

cookie()

cookie Function creates a new cookie instance:

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

## The csrf_field()

csrf_field function generates an HTML input form field hidden that contains the CSRF token value. For example, using Blade syntax:

{{ csrf_field() }}

##csrf_token()

csrf_token

Function to get the value of the current CSRF token:

$token = csrf_token();

##dd()

dd

The function prints out the given variables and ends the script execution:

dd($value);
dd($value1, $value2, $value3, ...);
If you do not stop executing the script, you can use

dump

function.

decrypt()

decrypt

function can use Laravel Encryption and decryption mechanism:

$decrypted = decrypt($encrypted_value);

##dispatch()

dispatch Function pushes the given task to the Laravel task queue:

dispatch(new App\Jobs\SendEmails);

dispatch_now()

dispatch_now Function runs the given task immediately and returns the value from the handle method:

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

##dump()

dump Print the given variable:

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

If you want to stop executing the script after printing, you can use the

dd function.

{Tip} You can use the

dump-server command in Artisan to intercept all dump calls and display them in a console window instead of browsing in the vessel.

##encrypt()

encrypt

Function Use Laravel's encryption and decryption mechanism to encrypt the given value:

$encrypted = encrypt($unencrypted_value);

##env()

env

The function can get the value of the environment variable configuration or return the default value:

$env = env('APP_ENV');// 返回 'production' 如果 APP_ENV 未设置的话...$env = env('APP_ENV', 'production');
{Note} If you execute

config during the deployment process: cache
command, then you should make sure to only call the

env function from the configuration file. Once the configuration is cached, the .env file will not be loaded again and all calls to the env function will return null.

##event()

event Function Dispatches the given event to the listener:

event(new UserRegistered($user));

##factory()

factory Function creates a model factory constructor based on the given class, name and quantity. It can be used for testing or data filling:
$user = factory(App\User::class)->make();

##filled()

filled

Whether the function returns is not "empty":
filled(0);
filled(true);
filled(false);
// true
filled('');
filled('   ');
filled(null);
filled(collect());
// false

blank The method has the opposite effect to

filled

.

##info()

info
function writes the information Enter log:

info('Some helpful information!');
You can pass an array of context data to this function:
info('User login attempt failed.', ['id' => $user->id]);

logger( )

logger
function can be used to write

debug level messages to the log:
logger('Debug message');

The context data array can be passed Give this function:

logger('User has logged in.', ['id' => $user->id]);
If this function is called without arguments, it will return the logger instance:
logger()->error('You are not allowed here.');

##

method_field()

method_field Number of lines Generates an HTML hidden field that contains HTTP actions that mimic the form. The following example uses Blade syntax:

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

##now()

now The function creates a new Illuminate\Support\Carbon instance based on the current time:

$now = now();

old()

old The function gets the old input value flushed into the session:

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

optional()

optional The function accepts any argument and allows you to access properties on the object or call its methods. If the given object is null, the property or method will return null instead of raising an error:

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

optional Functions also accept closures as its second parameter. If the value provided as the first argument is not null, the closure will be called:

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

##policy()

policy

Method gets the policy instance for the given class:

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

redirect()

redirect

The function returns the redirected HTTP response, or the redirector instance if called without parameters:

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

report()

report

The function uses the exception handler's report Method reported exception:

report($e);

##request()

request

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

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

##rescue()

rescue The function executes the given closure and catches any exceptions thrown during its execution. All exceptions caught will be passed to the

report

method of the exception handler; and then continue processing the request:

return rescue(function () {
    return $this->method();
  });
You can also pass a second parameter to it. This parameter will be used as the "default" value when executing the closure and throwing an exception:
return rescue(function () {
    return $this->method();
  }, false);
return rescue(function () {
    return $this->method();}, function () {
        return $this->failure();
     });

resolve()

resolve The function resolves an instance of a class or interface with the given name using the service container:

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

response()

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

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 given maximum attempt threshold is reached. If the callback does not throw an exception, the callback return value will be returned. If the callback throws an exception, it will be automatically retried. The maximum number of attempts has been reached, and an exception will be thrown:

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

##session()

session The function is used to get or set the session value:

$value = session('key');

You can pass an array of key-value pairs to this function to set the session value:

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

Call this function without parameters , then return the value stored in the session:

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

##tap()

tap

The function accepts two parameters: any $value and a closure. $value will be passed to the closure and returned by the tap function. Irrespective of the return value of the closure:

$user = tap(User::first(), function ($user) {
    $user->name = 'taylor';    
    $user->save();
  });
If no closure is passed to the

tap

function, any method can be called given the $value. The return value from calling this method is always $value, regardless of what the method returns in its definition. For example, the Eloquent update method specifies that it returns an integer. However, we can force the update method to return the model itself by calling the tap function chain:

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

today()

today

The function creates a new Illuminate\Support\Carbon instance based on the current date:

$today = today();

##throw_if()

The given Boolean expression results in true

, the

throw_if function throws the given exception:

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

##throw_unless( )

When the given Boolean expression results in false, the

throw_unless

function throws the given exception:

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

##trait_uses_recursive()

trait_uses_recursive Returns all traits used by the trait:
$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);

##transform()

transform

The function execution is based on (not empty)

closure

of the given value, and returns the result of the closure:

$callback = function ($value) {
    return $value * 2;
  };
$result = transform(5, $callback);
// 10
You can also pass a default value or Closure serves as the third parameter of the function. If the given value is empty, return the value:
$result = transform(null, $callback, 'The value is blank');
// The value is blank

validator()

validator The function creates a new validator instance based on the specified parameters. For convenience, you can use it instead of Validator facade:

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

#value()

value The function returns the given value. If closure is passed to this function, closure will be executed and the result of the closure call will be returned:

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

view()

view The function gets a view instance:

return view('auth.login');

with()

with The function returns the given value. If a Closure is passed to the second parameter, the result of Closure execution will be returned:

$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

This article was first published on