# 辅助函数
- [简介](#introduction)
- [可用方法](#available-methods)
## 简介
Laravel 包含各种各样的「全局」PHP辅助函数,框架本身也大量的使用了这些功能函数;如果你觉的方便,你可以在你的应用中任意使用这些函数.
## 可用方法
### 数组 & 对象
[array_add](#method-array-add)
[array_collapse](#method-array-collapse)
[array_divide](#method-array-divide)
[array_dot](#method-array-dot)
[array_except](#method-array-except)
[array_first](#method-array-first)
[array_flatten](#method-array-flatten)
[array_forget](#method-array-forget)
[array_get](#method-array-get)
[array_has](#method-array-has)
[array_last](#method-array-last)
[array_only](#method-array-only)
[array_pluck](#method-array-pluck)
[array_prepend](#method-array-prepend)
[array_pull](#method-array-pull)
[array_random](#method-array-random)
[array_set](#method-array-set)
[array_sort](#method-array-sort)
[array_sort_recursive](#method-array-sort-recursive)
[array_where](#method-array-where)
[array_wrap](#method-array-wrap)
[data_fill](#method-data-fill)
[data_get](#method-data-get)
[data_set](#method-data-set)
[head](#method-head)
[last](#method-last)
### 路径
[app_path](#method-app-path)
[base_path](#method-base-path)
[config_path](#method-config-path)
[database_path](#method-database-path)
[mix](#method-mix)
[public_path](#method-public-path)
[resource_path](#method-resource-path)
[storage_path](#method-storage-path)
### 字符串
[\__](#method-__)
[camel_case](#method-camel-case)
[class_basename](#method-class-basename)
[e](#method-e)
[ends_with](#method-ends-with)
[kebab_case](#method-kebab-case)
[preg_replace_array](#method-preg-replace-array)
[snake_case](#method-snake-case)
[starts_with](#method-starts-with)
[str_after](#method-str-after)
[str_before](#method-str-before)
[str_contains](#method-str-contains)
[str_finish](#method-str-finish)
[str_is](#method-str-is)
[str_limit](#method-str-limit)
[Str::orderedUuid](#method-str-ordered-uuid)
[str_plural](#method-str-plural)
[str_random](#method-str-random)
[str_replace_array](#method-str-replace-array)
[str_replace_first](#method-str-replace-first)
[str_replace_last](#method-str-replace-last)
[str_singular](#method-str-singular)
[str_slug](#method-str-slug)
[str_start](#method-str-start)
[studly_case](#method-studly-case)
[title_case](#method-title-case)
[trans](#method-trans)
[trans_choice](#method-trans-choice)
[Str::uuid](#method-str-uuid)
### URLs
[action](#method-action)
[asset](#method-asset)
[secure_asset](#method-secure-asset)
[route](#method-route)
[secure_url](#method-secure-url)
[url](#method-url)
### 其他
[abort](#method-abort)
[abort_if](#method-abort-if)
[abort_unless](#method-abort-unless)
[app](#method-app)
[auth](#method-auth)
[back](#method-back)
[bcrypt](#method-bcrypt)
[blank](#method-blank)
[broadcast](#method-broadcast)
[cache](#method-cache)
[class_uses_recursive](#method-class-uses-recursive)
[collect](#method-collect)
[config](#method-config)
[cookie](#method-cookie)
[csrf_field](#method-csrf-field)
[csrf_token](#method-csrf-token)
[dd](#method-dd)
[decrypt](#method-decrypt)
[dispatch](#method-dispatch)
[dispatch_now](#method-dispatch-now)
[dump](#method-dump)
[encrypt](#method-encrypt)
[env](#method-env)
[event](#method-event)
[factory](#method-factory)
[filled](#method-filled)
[info](#method-info)
[logger](#method-logger)
[method_field](#method-method-field)
[now](#method-now)
[old](#method-old)
[optional](#method-optional)
[policy](#method-policy)
[redirect](#method-redirect)
[report](#method-report)
[request](#method-request)
[rescue](#method-rescue)
[resolve](#method-resolve)
[response](#method-response)
[retry](#method-retry)
[session](#method-session)
[tap](#method-tap)
[today](#method-today)
[throw_if](#method-throw-if)
[throw_unless](#method-throw-unless)
[trait_uses_recursive](#method-trait-uses-recursive)
[transform](#method-transform)
[validator](#method-validator)
[value](#method-value)
[view](#method-view)
[with](#method-with)
## 方法列表
## 数组 & 对象
#### [`array_add()`](#collection-method.first-collection-method)
如果给定的键不存在数组中,那么`array_add`函数将会把给定的键/值对添加到数组中:
$array = array_add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
#### [ `array_collapse()`](#collection-method)
`array_collapse`函数将多个数组合并为一个数组;
$array = array_collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
#### [`array_divide()`](#collection-method)
`array_divide` 函数返回一个二维数组,一个值包含原始数组的键,另一个值包含原始数组的值.
[$keys, $values] = array_divide(['name' => 'Desk']);
// $keys: ['name'] 多维数组中的第0个值
// $values: ['Desk'] 多维数组中的第1个值
#### [`array_dot()`](#collection-method)
`array_dot`函数将多维数组中所有的键平铺到一维数组中,新数组使用「.」符号表示层级包含关系:
$array = ['products' => ['desk' => ['price' => 100]]];
$flattened = array_dot($array);
// ['products.desk.price' => 100]
#### [`array_except()`](#collection-method)
`array_except`函数从数组中删除给定的键/值对:
$array = ['name' => 'Desk', 'price' => 100];
$filtered = array_except($array, ['price']);
// ['name' => 'Desk']
#### [`array_first()`](#collection-method)
`array_first`函数返回数组中通过指定测试的第一个元素:
$array = [100, 200, 300];
$first = array_first($array, function ($value, $key) {
return $value >= 150;
});
// 200
将默认值作为第三个参数传递给该方法, 如果数组中没有值通过测试,则返回默认值.
$first = array_first($array, $callback, $default);
#### [`array_flatten()` ](#collection-method)
`array_flatten` 函数将多维数组中数组的值取出平铺为一维数组:
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$flattened = array_flatten($array);
// ['Joe', 'PHP', 'Ruby']
#### [`array_forget()`](#collection-method)
`array_forget`函数使用「点」符号从深度嵌套的数组中删除给定的键/值对:
$array = ['products' => ['desk' => ['price' => 100]]];
array_forget($array, 'products.desk');
// ['products' => []]
#### [`array_get()`](#collection-method)
`array_get` 函数使用「点」符号从深度嵌套的数组中根据指定键检索值:
$array = ['products' => ['desk' => ['price' => 100]]];
$price = array_get($array, 'products.desk.price');
// 100
`array_get` 函数也接受一个默认值,如果没有找到特定的键,将返回默认值:
$discount = array_get($array, 'products.desk.discount', 0);
// 0
#### [`array_has()` ](#collection-method)
`array_has` 函数使用「点」符号查找数组中是否存在指定的一个或多个键:
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
$contains = array_has($array, 'product.name');
// true
$contains = array_has($array, ['product.price', 'product.discount']);
// false
#### [`array_last()`](#collection-method)
`array_last` 函数返回数组中通过指定测试的最后一个元素:
$array = [100, 200, 300, 110];
$last = array_last($array, function ($value, $key) {
return $value >= 150;
});
// 300
将默认值作为第三个参数传递给该方法,如果没有值通过指定测试,则返回该默认值:
$last = array_last($array, $callback, $default);
#### [`array_only()`](#collection-method)
`array_only` 函数只从指定数组中返回指定的键/值对:
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
$slice = array_only($array, ['name', 'price']);
// ['name' => 'Desk', 'price' => 100]
#### [`array_pluck()`](#collection-method)
`array_pluck` 函数从数组中检索给定键的所有值:
$array = [
['developer' => ['id' => 1, 'name' => 'Taylor']],
['developer' => ['id' => 2, 'name' => 'Abigail']],
];
$names = array_pluck($array, 'developer.name');
// ['Taylor', 'Abigail']
你也可以指定获取的结果的键:
$names = array_pluck($array, 'developer.name', 'developer.id');
// [1 => 'Taylor', 2 => 'Abigail']
#### [`array_prepend()`](#collection-method)
`array_prepend`函数将一个值插入到数组的开始位置:
$array = ['one', 'two', 'three', 'four'];
$array = array_prepend($array, 'zero');
// ['zero', 'one', 'two', 'three', 'four']
如果你需要,你可以指定你插入值的键:
$array = ['price' => 100];
$array = array_prepend($array, 'Desk', 'name');
// ['name' => 'Desk', 'price' => 100]
#### [`array_pull()`](#collection-method)
`array_pull` 函数从数组中返回指定键的值并删除此键/值对:
$array = ['name' => 'Desk', 'price' => 100];
$name = array_pull($array, 'name');
// $name: Desk
// $array: ['price' => 100]
默认值可以作为第三个参数传递给该方法,如果键不存在,则返回该值:
$value = array_pull($array, $key, $default);
#### [`array_random()`](#collection-method)
`array_random` 函数从数组中随机返回一个值:
$array = [1, 2, 3, 4, 5];
$random = array_random($array);
// 4 - (retrieved randomly)
你也可以将返回值的数量作为可选的第二个参数传递给该方法,请注意,提供这个参数会返回一个数组,即便是你只需要一项:
$items = array_random($array, 2);
// [2, 5] - (retrieved randomly)
#### [`array_set()`](#collection-method)
`array_set` 函数使用「.」符号在多维数组中设置指定键的值:
$array = ['products' => ['desk' => ['price' => 100]]];
array_set($array, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]
#### [`array_sort()`](#collection-method)
`array_sort`函数根据数组的值对数组进行排序:
$array = ['Desk', 'Table', 'Chair'];
$sorted = array_sort($array);
// ['Chair', 'Desk', 'Table']
你也可以根据给定闭包返回的结果对数组进行排序:
$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()`](#collection-method)
`array_sort_recursive` 函数使用 `sort`函数对数组进行递归排序:
$array = [
['Roman', 'Taylor', 'Li'],
['PHP', 'Ruby', 'JavaScript'],
];
$sorted = array_sort_recursive($array);
/*
[
['Li', 'Roman', 'Taylor'],
['JavaScript', 'PHP', 'Ruby'],
]
*/
#### [`array_where()`](#collection-method)
`array_where`函数使用给定闭包返回的结果过滤数组:
$array = [100, '200', 300, '400', 500];
$filtered = array_where($array, function ($value, $key) {
return is_string($value);
});
// [1 => '200', 3 => '400']
#### [`array_wrap()`](#collection-method)
`array_wrap`函数将给定的值变为一个数组, 如果给定的值已经是数组,则不改变:
$string = 'Laravel';
$array = array_wrap($string);
// ['Laravel']
如果给定的值是空,则返回一个空数组:
$nothing = null;
$array = array_wrap($nothing);
// []
#### [`data_fill()`](#collection-method)
`data_fill` 函数使用「.」符号在多维数组或对象内设置缺省值:
$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]]]
这个函数还接受星号「*」作为通配符,相应的填充目标:
$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()`](#collection-method)
`data_get`函数使用「.」符号从多维数组或对象中检索值:
$data = ['products' => ['desk' => ['price' => 100]]];
$price = data_get($data, 'products.desk.price');
// 100
`data_get` 函数也可以接收一个默认值, 如果找不到指定的键,则返回默认值:
$discount = data_get($data, 'products.desk.discount', 0);
// 0
#### [`data_set()`](#collection-method)
`data_set` 函数使用「.」符号在多维数组或对象中设置一个值:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]
该函数也可以接收通配符,相应的在指定键上设置值:
$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],
],
]
*/
默认情况下, 所有现有值都会被覆盖, 如果你只希望设置不存在的值,你可以选择`false`作为第四个参数传递给该方法:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200, false);
// ['products' => ['desk' => ['price' => 100]]]
#### [`head()`](#collection-method)
`head` 函数返回给定数组中的第一个元素:
$array = [100, 200, 300];
$first = head($array);
// 100
#### [`last()`](#collection-method)
`last` 函数返回给定数组中的最后一个元素:
$array = [100, 200, 300];
$last = last($array);
// 300
## 路径
#### [`app_path()`](#collection-method)
`app_path`函数返回`app`目录的完整路径.你也可以使用 `app_path`函数来设置应用程序`app`目录的完整路径:
$path = app_path();
$path = app_path('Http/Controllers/Controller.php');
#### [`base_path()`](#collection-method)
`base_path`函数返回项目根目录的完整路径.你也可以使用`base_path`函数设置项目根目录的完整路径:
$path = base_path();
$path = base_path('vendor/bin');
#### [`config_path()`](#collection-method)
`config_path`函数返回`config` 目录的完整路径.你也可以使用`config_path`函数设置应用程序`config` 目录中给定文件的完整路径:
$path = config_path();
$path = config_path('app.php');
#### [`database_path()`](#collection-method)
`database_path` 函数返回`database`目录的完整路径.你也可以使用 `database_path`函数来设置`database`目录中给定文件的完整路径:
$path = database_path();
$path = database_path('factories/UserFactory.php');
#### [`mix()`](#collection-method)
`mix`函数返回 [版本化 Mix 文件](/docs/{{version}}/mix) 的路径:
$path = mix('css/app.css');
#### [`public_path()`](#collection-method)
`public_path`函数返回`public`目录的完整路径.你也可以使用 `public_path`函数来生成`public`目录中给定文件的完整路径:
$path = public_path();
$path = public_path('css/app.css');
#### [`resource_path()`](#collection-method)
`resource_path` 函数返回`resources`目录的完整路径.你也可以使用 `resource_path` 函数来生成资源文件中给定文件的完整路径:
$path = resource_path();
$path = resource_path('assets/sass/app.scss');
#### [`storage_path()`](#collection-method)
`storage_path` 函数返回 `storage`目录的完整路径.你也可以使用 `storage_path`函数来设置存储目录下指定文件的完整路径 :
$path = storage_path();
$path = storage_path('app/file.txt');
## 字符串
#### [`__()`](#collection-method)
`__` 函数使用你的[本地化文件](/docs/{{version}}/localization)来翻译给定的翻译字符串或翻译键:
echo __('Welcome to our application');
echo __('messages.welcome');
如果指定的翻译字符串或翻译键不存在,`__` 函数将返回给定的值.所以,按照上面的例子,如果翻译键 `messages.welcome`不存在,`__` 函数会将其直接返回.
#### [`camel_case()`](#collection-method)
`camel_case` 函数将给定字符串「短横式」转化为 `camelCase`「驼峰式」:
$converted = camel_case('foo_bar');
// fooBar
#### [`class_basename()`](#collection-method)
`class_basename`函数返回被删除了命名空间的指定类的类名:
$class = class_basename('Foo\Bar\Baz');
// Baz
#### [`e()`](#collection-method)
`e` 函数将默认值为`true`的 `double_encode` 选项值改为`false`来运行 `PHP`的 `htmlspecialchars`函数 :
echo e('foo');
// foo
#### [`ends_with()`](#collection-method)
`ends_with`函数判断指定的字符串是否以给定的值结尾:
$result = ends_with('This is my name', 'name');
// true
#### [`kebab_case()`](#collection-method)
`kebab_case`函数将给定的「驼峰式」字符串转化为「短横式」字符串:
$converted = kebab_case('fooBar');
// foo-bar
#### `preg_replace_array()` {#collection-method}
`preg_replace_array` 函数使用数组顺序替换字符串中的给定模式:
$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 之间进行
#### `snake_case()` {#collection-method}
`snake_case` 函数将给定的字符串转换为 「蛇式」:
$converted = snake_case('fooBar');
// foo_bar
#### `starts_with()` {#collection-method}
`starts_with` 函数判断给定的字符串的开头是否是指定值:
$result = starts_with('This is my name', 'This');
// true
#### `str_after()` {#collection-method}
`str_after` 函数返回在字符串中指定值之后的所有内容:
$slice = str_after('This is my name', 'This is');
// ' my name'
#### `str_before()` {#collection-method}
`str_before` 函数返回在字符串中指定值之前的所有内容:
$slice = str_before('This is my name', 'my name');
// 'This is '
#### `str_contains()` {#collection-method}
`str_contains` 函数判断给定的字符串是否包含给定的值(区分大小写):
$contains = str_contains('This is my name', 'my');
// true
你也可以传递一个数组形式的值来判断字符串中是否包含任何值:
$contains = str_contains('This is my name', ['my', 'foo']);
// true
#### `str_finish()` {#collection-method}
`str_finish` 函数将给定的字符串以给定的值结尾返回(如果它尚未以给定值结尾):
$adjusted = str_finish('this/string', '/');
// this/string/
$adjusted = str_finish('this/string/', '/');
// this/string/
#### `str_is()` {#collection-method}
`str_is` 函数判断给定的字符串是否匹配给定的模式。星号 `*` 可以用来表示通配符:
$matches = str_is('foo*', 'foobar');
// true
$matches = str_is('baz*', 'foobar');
// false
#### `str_limit()` {#collection-method}
`str_limit` 函数按给定的长度截断给定的字符串:
$truncated = str_limit('The quick brown fox jumps over the lazy dog', 20);
// The quick brown fox...
你也可以传递第三个参数来改变将被追加到最后的字符串:
$truncated = str_limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
// The quick brown fox (...)
#### `Str::orderedUuid()` {#collection-method}
`Str::orderedUuid` 方法高效生成一个可存储在索引数据库列中的「第一时间」UUID:
use Illuminate\Support\Str;
return (string) Str::orderedUuid();
#### `str_plural()` {#collection-method}
`str_plural` 函数将字符串转换为复数形式。该函数目前仅支持英文:
$plural = str_plural('car');
// cars
$plural = str_plural('child');
// children
你可以提供一个整数作为函数的第二个参数来检索字符串的单数或复数形式:
$plural = str_plural('child', 2);
// children
$plural = str_plural('child', 1);
// child
#### `str_random()` {#collection-method}
`str_random` 函数生成一个指定长度的随机字符串。这个函数用 PHP 的 `random_bytes` 函数:
$random = str_random(40);
#### `str_replace_array()` {#collection-method}
`str_replace_array` 函数使用数组顺序替换字符串中的给定值:
$string = '该活动将于 ? 至 ? 之间举行';
$replaced = str_replace_array('?', ['8:30', '9:00'], $string);
// 该活动将于 8:30 至 9:00 之间举行
#### `str_replace_first()` {#collection-method}
`str_replace_first` 函数替换字符串中给定值的第一个匹配项:
$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()` {#collection-method}
`str_replace_last` 函数替换字符串中最后一次出现的给定值:
$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()` {#collection-method}
`str_singular` 函数将字符串转换为单数形式。该函数目前仅支持英文:
$singular = str_singular('cars');
// car
$singular = str_singular('children');
// child
#### `str_slug()` {#collection-method}
`str_slug` 函数将给定的字符串生成一个 URL 友好的「slug」:
$slug = str_slug('Laravel 5 Framework', '-');
// laravel-5-framework
#### `str_start()` {#collection-method}
`str_start` 函数将给定值添加到给定字符串的开始位置(如果字符串尚未以给定值开始)
$adjusted = str_start('this/string', '/');
// /this/string
$adjusted = str_start('/this/string', '/');
// /this/string
#### `studly_case()` {#collection-method}
`studly_case` 函数将给定的字符串转换为 「变种驼峰命名」:
$converted = studly_case('foo_bar');
// FooBar
#### `title_case()` {#collection-method}
`title_case` 函数将给定的字符串转换为「首字母大写」:
$converted = title_case('a nice title uses the correct case');
// A Nice Title Uses The Correct Case
#### `trans()` {#collection-method}
`trans` 函数使用你的 [本地文件](/docs/{{version}}/localization) 来翻译给定的翻译字符串或翻译健:
echo trans('messages.welcome');
如果指定的翻译健不存在,则 `trans` 方法会简单地返回给定的健。所以,就上面的例子而言,如果翻译健不存在,`trans` 方法会返回 `messages.welcome`。
#### `trans_choice()` {#collection-method}
`trans_choice` 函数根据词形变化来翻译给定的翻译健:
echo trans_choice('messages.notifications', $unreadCount);
如果指定的翻译健不存在,`trans_choice` 方法会简单地返回给定的健。所以,按照上面的例子,如果翻译健不存在,`trans_choice` 方法会返回 `messages.notifications`。
#### `Str::uuid()` {#collection-method}
`Str::uuid` 方法生成一个 UUID(版本 4):
use Illuminate\Support\Str;
return (string) Str::uuid();
## URLs
#### `action()` {#collection-method}
`action` 函数为指定的控制器动作生成一个 URL。你不需要传递完整的控制器命名空间。只需要传递相对于 `App\Http\Controllers` 命名空间控制器类名称:
$url = action('HomeController@index');
$url = action([HomeController::class, 'index']);
如果该方法接受路由参数,则可以将它们作为方法的第二个参数传递:
$url = action('UserController@profile', ['id' => 1]);
#### `asset()` {#collection-method}
`asset` 函数使用当前请求的协议(HTTP 或 HTTPS)为资源文件生成 URL:
$url = asset('img/photo.jpg');
#### `secure_asset()` {#collection-method}
`secure_asset` 函数使用 HTTPS 协议为资源文件生成 URL:
$url = secure_asset('img/photo.jpg');
#### `route()` {#collection-method}
`route` 函数为给定的命名路由生成一个 URL:
$url = route('routeName');
如果路由接受参数,则可以将它们作为方法的第二个参数传递:
$url = route('routeName', ['id' => 1]);
默认情况下,`route` 函数生成的是绝对 URL。如果你想生成一个相对 URL,你可以传递 `false` 作为第三个参数:
$url = route('routeName', ['id' => 1], false);
#### `secure_url()` {#collection-method}
`secure_url` 函数为给定的路径生成一个标准的 HTTPS URL:
$url = secure_url('user/profile');
$url = secure_url('user/profile', [1]);
#### `url()` {#collection-method}
`url` 函数生成给定路径的标准 URL:
$url = url('user/profile');
$url = url('user/profile', [1]);
如果没有提供路径,则返回 `Illuminate\Routing\UrlGenerator` 实例:
$current = url()->current();
$full = url()->full();
$previous = url()->previous();
## 其他
#### `abort()` {#collection-method}
`abort` 函数抛出 [异常处理](/docs/{{version}}/errors#the-exception-handler) 程序呈现的 [HTTP 异常](/docs/{{version}}/errors#http-exceptions)
abort(403);
你也可以提供额外的响应文本和自定义响应标头:
abort(403, 'Unauthorized.', $headers);
#### `abort_if()` {#collection-method}
如果给定的布尔表达式计算结果为 `true`,`abort_if` 函数将抛出一个 HTTP 异常:
abort_if(! Auth::user()->isAdmin(), 403);
和 `abort` 方法一样,你也可以提供异常的响应文本作为第三个参数,并提供一个自定义响应头数据作为第四个参数。
#### `abort_unless()` {#collection-method}
如果给定的布尔表达式计算结果为 `false`,`abort_unless` 函数将抛出一个 HTTP 异常:
abort_unless(Auth::user()->isAdmin(), 403);
和 `abort` 方法一样,你也可以提供异常的响应文本作为第三个参数,并提供一个自定义响应头数组作为第四个参数。
#### `app()` {#collection-method}
`app` 函数返回 [服务容器](/docs/{{version}}/container) 实例:
$container = app();
你可以传递一个类或接口名称来从容器中解析它:
$api = app('HelpSpot\API');
#### `auth()` {#collection-method}
`auth` 函数返回一个 [认证](/docs/{{version}}/authentication) 实例。为了方便起见,你可以使用它来替代 `Auth` Facade:
$user = auth()->user();
如果需要,你可以指定你想要访问的认证实例:
$user = auth('admin')->user();
#### `back()` {#collection-method}
`back` 函数生成一个 [重定向 HTTP 响应](/docs/{{version}}/responses#redirects) 到用户之前的位置:
return back($status = 302, $headers = [], $fallback = false);
return back();
#### `bcrypt()` {#collection-method}
`bcrypt` [哈希](/docs/{{version}}/hashing) 使用 Bcrypt 对给定的值进行散列。你可以使用它替代`Hash` Facade:
$password = bcrypt('my-secret-password');
#### `broadcast()` {#collection-method}
`broadcast` 函数将 [广播](/docs/{{version}}/broadcasting) 给定的 [事件](/docs/{{version}}/events) 到它的监听器:
broadcast(new UserRegistered($user));
#### [`blank()`](#collection-method)
`blank`函数判断给定的值是否为空:
blank('');
blank(' ');
blank(null);
blank(collect());
// true
blank(0);
blank(true);
blank(false);
// false
如果想使用与`blank`函数相反的方法,请看[`filled`](#method-filled) 方法.
#### [`cache()`](#collection-method)
`cache`函数可以从[缓存](/docs/{{version}}/cache)中获取值.如果缓存中给定的键不存在,将返回一个可选的默认值:
$value = cache('key', 'default');
你可以通过向函数添加键值对数组来设置缓存项.与此同时,你还应该传递有效的分钟数或者缓存的持续时间来设置缓存过期时间 :
cache(['key' => 'value'], 5);
cache(['key' => 'value'], now()->addSeconds(10));
#### [`class_uses_recursive()`](#collection-method)
`class_uses_recursive` 函数返回一个类使用的所有 traits ,包括它所有父类使用的 traits:
$traits = class_uses_recursive(App\User::class);
#### [`collect()`](#collection-method)
`collect`函数根据给定的值创建一个 [集合](/docs/{{version}}/collections) 实例:
$collection = collect(['taylor', 'abigail']);
#### [`config()`](#collection-method)
`config` 函数获取 [配置](/docs/{{version}}/configuration) 变量的值. 可以使用「点」语法访问配置的值, 其中包括文件的名称和访问的选项,如果访问的配置选项不存在,你可以指定一个默认值并且返回这个默认值.
$value = config('app.timezone');
$value = config('app.timezone', $default);
你也可以在运行时通过传递一个键/值对数组来设置配置变量:
config(['app.debug' => true]);
#### [`cookie()`](#collection-method)
`cookie` 函数创建一个新的 [cookie](/docs/{{version}}/requests#cookies) 实例:
$cookie = cookie('name', 'value', $minutes);
#### [`csrf_field()`](#collection-method)
`csrf_field` 函数生成一个包含CSRF令牌值的HTML 输入表单字段 `hidden` ,例如,使用 [Blade 语法](/docs/{{version}}/blade):
{{ csrf_field() }}
#### [`csrf_token()`](#collection-method)
`csrf_token` 函数获取当前CSRF令牌的值:
$token = csrf_token();
#### [`dd()`](#collection-method)
`dd` 函数打印输出给定的变量并且结束脚本运行:
dd($value);
dd($value1, $value2, $value3, ...);
如果你不停止执行脚本,那么可以使用 [`dump`](#method-dump) 函数.
#### [`decrypt()`](#collection-method)
`decrypt` 函数可以使用 Laravel的 [加解密机制](/docs/{{version}}/encryption)来解密给定的值:
$decrypted = decrypt($encrypted_value);
#### [`dispatch()`](#collection-method)
`dispatch` 函数将给定的 [任务](/docs/{{version}}/queues#creating-jobs) 推送到Laravel [任务队列](/docs/{{version}}/queues) 中:
dispatch(new App\Jobs\SendEmails);
#### [`dispatch_now()`](#collection-method)
`dispatch_now` 函数立即运行给定的 [任务](/docs/{{version}}/queues#creating-jobs) ,并从其 `handle` 方法返回值:
$result = dispatch_now(new App\Jobs\SendEmails);
#### [`dump()`](#collection-method)
`dump` 函数打印给定的变量:
dump($value);
dump($value1, $value2, $value3, ...);
如果你想要在打印后停止执行脚本,可以使用 [`dd`](#method-dd) 函数.
> {tip} 你可以使用 Artisan中的 `dump-server` 命令拦截所有 `dump` 调用, 并将它们显式在控制台窗口而不是浏览器中.
#### [`encrypt()`](#collection-method)
`encrypt` 函数使用Laravel的 [加解密机制](/docs/{{version}}/encryption) 对给定的值进行加密:
$encrypted = encrypt($unencrypted_value);
#### [`env()`](#collection-method)
`env` 函数可以获取 [环境变量](/docs/{{version}}/configuration#environment-configuration) 配置的值或者返回默认值:
$env = env('APP_ENV');
// Returns 'production' if APP_ENV is not set...
$env = env('APP_ENV', 'production');
> {note} 如果你在部署过程中执行了 `config:cache` 命令 ,那么你应该确保只从配置文件中调用 `env` 函数.一旦配置被添加到缓存中,`.env` 文件则不会再次被加载,并且所有对 `env` 函数的调用将返回 `null`.
#### [`event()`](#collection-method)
`event` 函数将给定的 [事件](/docs/{{version}}/events) 分派给它的监听器:
event(new UserRegistered($user));
#### [`factory()`](#collection-method)
`factory`函数根据给定的类,名称,数量创建一个模型工厂构建器,它可以在 [测试](/docs/{{version}}/database-testing#writing-factories) 或者 [数据填充](/docs/{{version}}/seeding#using-model-factories) 中使用:
$user = factory(App\User::class)->make();
#### [`filled()`](#collection-method)
`filled`函数判断给定的值不为「空」:
filled(0);
filled(true);
filled(false);
// true
filled('');
filled(' ');
filled(null);
filled(collect());
// false
要使用与`filled`函数相反的功能, 请看[`blank`](#method-blank) 方法.
#### [`info()`](#collection-method)
`info` 函数将信息写入 [日志](/docs/{{version}}/errors#logging):
info('Some helpful information!');
在上下文中有关联的数组也可以传递给数组:
info('User login attempt failed.', ['id' => $user->id]);
#### [`logger()`](#collection-method)
`logger` 函数可以将一个 `debug` 级别的消息写入到 [日志](/docs/{{version}}/errors#logging)中:
logger('Debug message');
有前后关系的数组也可以传值给数组:
logger('User has logged in.', ['id' => $user->id]);
如果没有传递任何参数给函数,则会返回 [日志](/docs/{{version}}/errors#logging) 的实例:
logger()->error('You are not allowed here.');
#### [`method_field()`](#collection-method)
`method_field` 函数生成一个HTML `hidden` 输入框包含表单的HTTP动作的欺骗值.例如,使用 [Blade 语法](/docs/{{version}}/blade):
#### [`now()`](#collection-method)
`now` 函数为当前时间创建一个新的 `Illuminate\Support\Carbon` 实例:
$now = now();
#### [`old()`](#collection-method)
`old` 函数 [检索](/docs/{{version}}/requests#retrieving-input) 会话中闪存的 [旧输入](/docs/{{version}}/requests#old-input) 值:
$value = old('value');
$value = old('value', 'default');
#### [`optional()`](#collection-method)
`optional` 函数可以接收任何参数,并且允许你访问该对象的属性或者调用其方法,如果给定的对象是`null`,属性和方法将返回`null`,而不会报错:
return optional($user->address)->street;
{!! old('name', optional($user)->name) !!}
`optional` 函数也可以接收一个闭包作为第二个参数,如果给定的第一个参数不为空,则执行闭包:
return optional(User::find($id), function ($user) {
return new DummyUser;
});
#### [`policy()`](#collection-method)
`policy` 方法为指定的类检索这个类的 [策略](/docs/{{version}}/authorization#creating-policies) 实例:
$policy = policy(App\User::class);
#### [`redirect()`](#collection-method)
`redirect` 函数返回一个 [重定向 HTTP 响应](/docs/{{version}}/responses#redirects), 或者如果没有传递参数,则返回重定向实例:
return redirect($to = null, $status = 302, $headers = [], $secure = null);
return redirect('/home');
return redirect()->route('route.name');
#### [`report()`](#collection-method)
`report` 函数将会使用 [异常处理程序](/docs/{{version}}/errors#the-exception-handler) 里的 `report` 方法来报告异常:
report($e);
#### [`request()`](#collection-method)
`request`函数返回当前获取的 [请求](/docs/{{version}}/requests) 实例或者获取输入项:
$request = request();
$value = request('key', $default);
#### [`rescue()`](#collection-method)
`rescue` 函数执行给定的闭包并且捕获在执行期间发生的任何异常.所有被捕获的异常将会被发送到 [异常处理程序 ](/docs/{{version}}/errors#the-exception-handler) 的 `report` 方法; 然而,该请求还会继续执行:
return rescue(function () {
return $this->method();
});
你也可以向 `rescue` 函数传递第二个参数,这个参数将作为默认值,如果在执行闭包时发生异常,返回默认值:
return rescue(function () {
return $this->method();
}, false);
return rescue(function () {
return $this->method();
}, function () {
return $this->failure();
});
#### [`resolve()`](#collection-method)
`resolve` 函数使用 [服务容器](/docs/{{version}}/container)将给定的类或接口解析为其实例:
$api = resolve('HelpSpot\API');
#### [`response()`](#collection-method)
`response` 函数可以创建 [响应](/docs/{{version}}/responses) 实例或者获取响应工厂的实例:
return response('Hello World', 200, $headers);
return response()->json(['foo' => 'bar'], 200, $headers);
#### [`retry()`](#collection-method)
`retry` 函数尝试执行给定的回调,直到达到给定的最大尝试次数.如果回调没有抛出异常,则返回设置的返回值, 如果回调抛出了异常,将会自动重试执行.如果重试超过最大尝试次数,将会抛出异常.
return retry(5, function () {
// Attempt 5 times while resting 100ms in between attempts...
}, 100);
#### [`session()`](#collection-method)
`session` 函数可以用来获取或者设置 [session](/docs/{{version}}/session) 值:
$value = session('key');
你可以通过传一个键/值对数组给函数来设置值:
session(['chairs' => 7, 'instruments' => 3]);
如果没有给函数传值,则会返回 Session 存储:
$value = session()->get('key');
session()->put('key', $value);
#### [`tap()`](#collection-method)
`tap` 函数接收两个参数:一个任意的 `$value` 和一个闭包. 这个值将会传递给闭包,并且由 `tap` 函数返回.不需要在闭包中使用 `return` 返回值:
$user = tap(User::first(), function ($user) {
$user->name = 'taylor';
$user->save();
});
如果没有闭包传递给 `tap` 函数,你可以对给定的`$value` 调用任何方法,无论这些方法在实际定义中返回什么,调用方法的返回值总是 `$value`,例如, Eloquent 的`update` 方法总是返回一个整数. 但是,我们可以通过 `tap` 函数, 链接`update` 方法调用,迫使它返回模型自身:
$user = tap($user)->update([
'name' => $name,
'email' => $email,
]);
#### [`today()`](#collection-method)
`today` 函数为当前日期创建一个新的`Illuminate\Support\Carbon` 实例 :
$today = today();
#### [`throw_if()`](#collection-method)
如果给定的布尔表达式的结果为 `true`,则 `throw_if` 函数会抛出指定的异常:
throw_if(! Auth::user()->isAdmin(), AuthorizationException::class);
throw_if(
! Auth::user()->isAdmin(),
AuthorizationException::class,
'You are not allowed to access this page'
);
#### [`throw_unless()`](#collection-method)
如果给定的布尔表达式的结果为 `false`,则 `throw_unless` 函数会抛出指定的异常:
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()`](#collection-method)
`trait_uses_recursive` 函数返回一个类使用的所有trait:
$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);
#### [`transform()`](#collection-method)
`transform` 函数如果传递的参数不为空,(可以通过 [blank](#method-blank) 函数判断) ,则对指定值开始执行 `Closure`,并且返回 `Closure`的结果:
$callback = function ($value) {
return $value * 2;
};
$result = transform(5, $callback);
// 10
默认值或者闭包可以以第三个参数的方式传递给该函数,默认值在给定值为空的情况下返回:
$result = transform(null, $callback, 'The value is blank');
// The value is blank
#### [`validator()`](#collection-method)
`validator` 函数通过给定的参数创建一个新的 [验证器](/docs/{{version}}/validation) 实例 ,方便起见,你可以用它来替代 `Validator` 代理 :
$validator = validator($data, $rules, $messages);
#### [`value()`](#collection-method)
`value` 函数返回给定的值,然而,如果传递了参数 `Closure` 给函数,将会返回 `Closure` 执行的结果:
$result = value(true);
// true
$result = value(function () {
return false;
});
// false
#### [`view()`](#collection-method)
`view` 函数获取一个 [视图](/docs/{{version}}/views) 实例:
return view('auth.login');
#### [`with()`](#collection-method)
`with` 函数会返回给定的值.如果传递了一个 `Closure` 作为第二个参数,那么会返回`Closure` 执行的结果:
$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