Auxiliary function: a sharp tool to simplify Laravel code writing


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

Array function

array_add()

array_add Function to add the given key value pair to the array -- if the given key does not exist:

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

array_collapse()

array_collapse The function combines multiple arrays into one:

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

array_divide()

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

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

array_dot()

array_dot The function uses "." Number will convert multidimensional array to one-dimensional array:

 $array = ['products' => ['desk' => ['price' => 100]]]; $flattened = array_dot($array); // ['products.desk.price' => 100]

array_except()

array_except Function to remove the given key value pair from the array:

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

array_first()

array_first The function returns the first element of the test array:

 $array = [100, 200, 300]; $value = array_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:

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

array_flatten()

array_flatten The function converts a multidimensional array to a one-dimensional array:

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

array_forget()

array_forget The function uses "." Number to remove the given key value pair from the nested array:

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

array_get()

array_get Method Use "." Number to get a value from a nested array:

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

array_get The function also receives a default value. If the specified key does not exist, it returns the default value:

 $value = array_get($array, 'products.desk.discount', 0); // 0

array_has()

array_has The function uses "." to check whether the given data item exists in the array:

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

array_last()

array_last The function returns the last element of the filtered array:

 $array = [100, 200, 300, 110]; $value = array_last($array, function ($value, $key) { return $value >= 150; }); // 300

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

 $last = array_last($array, $callback, $default);

array_only()

array_only Method only returns the specified key value pair from the given array:

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

array_pluck()

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

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

You can also specify the key to return results:

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

array_prepend()

array_prepend The function pushes the data item to the beginning of the array:

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

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

 $array = ['price' => 100]; $array = array_prepend($array, 'Desk', 'name'); // ['name' => 'Desk', 'price' => 100]

array_pull()

array_pull The function returns and removes key value pairs from the array:

 $array = ['name' => 'Desk', 'price' => 100]; $name = array_pull($array, 'name'); // $name: Desk // $array: ['price' => 100]

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

 $value = array_pull($array, $key, $default);

array_random()

array_random The function returns a random value from an array:

 $array = [1, 2, 3, 4, 5]; $random = array_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:

 $items = array_random($array, 2); // [2, 5] - (retrieved randomly)

array_set()

array_set The function is used to use "." in nested arrays Number setting value:

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

array_sort()

array_sort The function sorts the array by value:

 $array = ['Desk', 'Table', 'Chair']; $sorted = array_sort($array); // ['Chair', 'Desk', 'Table']

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

 $array = [ ['name' => 'Desk'], ['name' => 'Table'], ['name' => 'Chair'], ]; $sorted = array_values(array_sort($array, function ($value) { return $value['name']; })); /* [ ['name' => 'Chair'], ['name' => 'Desk'], ['name' => 'Table'], ] */

array_sort_recursive()

array_sort_recursive Function Usage sort Function to sort the array recursively:

 $array = [ ['Roman', 'Taylor', 'Li'], ['PHP', 'Ruby', 'JavaScript'], ]; $array = array_sort_recursive($array); /* [ ['Li', 'Roman', 'Taylor'], ['JavaScript', 'PHP', 'Ruby'], ] */

array_where()

array_where The function uses the given closure to filter the array:

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

array_wrap()

array_wrap The function wraps the given value into an array. If the given value is already an array, it remains unchanged:

 $string = 'Laravel'; $array = array_wrap($string); // ['Laravel']

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

 $nothing = null; $array = array_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:

 mix($file);

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('assets/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

camel_case()

camel_case The function converts the given string into a string that conforms to the hump naming rule:

 $camel = camel_case('foo_bar'); // fooBar

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>'); // &lt; html&gt; foo&lt;/ html&gt;

ends_with()

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

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

kebab_case()

kebab_case The function converts the given string to a dash delimited string:

 $converted = kebab_case('fooBar'); // foo-bar

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

snake_case()

snake_case The function converts the given string to an underscore delimited string:

 $snake = snake_case('fooBar'); // foo_bar

starts_with()

starts_with The function determines whether the given string starts with the given value:

 $result = starts_with('This is my name', 'This'); // true

str_after()

str_after The function returns all characters after the given value in the string:

 $slice = str_after('This is my name', 'This is'); // ' my name'

str_before()

str_before The function returns all characters before the given value of the string:

 $slice = str_before('This is my name', 'my name'); // 'This is '

str_contains()

str_contains The function determines whether a given string contains a given value (case sensitive):

 $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:

 $contains = str_contains('This is my name', ['my', 'foo']); // true

str_finish()

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

 $adjusted = str_finish('this/string', '/'); // this/string/ $adjusted = str_finish('this/string/', '/'); // this/string/

str_is()

str_is Function to determine whether a given string matches a given pattern. Asterisks can be used to indicate wildcards:

 $value = str_is('foo*', 'foobar'); // true $value = str_is('baz*', 'foobar'); // false

str_limit()

str_limit Function to truncate a string at the specified length:

 $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:

 $truncated = str_limit('The quick brown fox jumps over the lazy dog', 20, ' (...)'); // The quick brown fox (...)

str_plural()

str_plural The function converts a string to a complex number. Currently, this function only supports English:

 $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:

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

str_random()

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

 $string = str_random(40);

str_replace_array()

str_replace_array The function replaces the given value in a string sequence with an array:

 $string = 'The event will take place between ?  and ?'; $replaced = str_replace_array('?', ['8:30', '9:00'], $string); // The event will take place between 8:30 and 9:00

str_replace_first()

str_replace_first The function replaces the first occurrence of the value in the string:

 $replaced = str_replace_first('the', 'a', 'the quick brown fox jumps over the lazy dog'); // a quick brown fox jumps over the lazy dog

str_replace_last()

str_replace_last The function replaces the last occurrence of the value in the string:

 $replaced = str_replace_last('the', 'a', 'the quick brown fox jumps over the lazy dog'); // the quick brown fox jumps over a lazy dog

str_singular()

str_singular The function converts a string to a singular form. At present, this function only supports English:

 $singular = str_singular('cars'); // car $singular = str_singular('children'); // child

str_slug()

str_slug The function generates a URL friendly format for the given string:

 $title = str_slug("Laravel 5 Framework", "-"); // laravel-5-framework

str_start()

If the string does not start with the given value str_start The function will add the given value to the front of the string:

 $adjusted = str_start('this/string', '/'); // /this/string $adjusted = str_start('/this/string/', '/'); // /this/string

studly_case()

studly_case The function converts the given string to the format of capitalizing the first letter of a word:

 $value = studly_case('foo_bar'); // FooBar

title_case()

title_case Function to convert a string to Title Form:

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

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 ');

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');

secure_asset()

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

 echo secure_asset('foo/bar.zip', $title, $attributes = []);

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 The function returns the service container instance:

 $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 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');

broadcast()

broadcast function radio broadcast given event To listener:

 broadcast(new UserRegistered($user));

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.

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 (minutes) 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 to obtain the value of the configuration variable. The configuration value can be obtained 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()

The 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.

encrypt()

encrypt The function encrypts the given string using the Larravel encryptor:

 $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 logger 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 The function obtains the value stored in a one-time session:

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

optional()

The optional function takes arbitrary parameters and allows you to access the properties on the 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) !!}

policy()

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

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

redirect()

redirect The function returns an HTTP redirect response. If it does not take parameters, it returns a 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 The function uses the service container to 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, ]);

today()

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

 $today = today();

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' );

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: Collection: add wings to PHP arrays

>>Next: Integrated Flysystem for advanced operation of file system