辅助函数
介绍
Laravel 包含多种全局 "辅助" PHP 函数。许多这些函数被框架本身使用;然而,如果您觉得方便,您可以在自己的应用程序中使用它们。
可用方法
数组与对象
array_addarray_collapsearray_dividearray_dotarray_exceptarray_firstarray_flattenarray_forgetarray_getarray_hasarray_lastarray_onlyarray_pluckarray_prependarray_pullarray_randomarray_setarray_sortarray_sort_recursivearray_wherearray_wrapdata_filldata_getdata_setheadlast
路径
字符串
__camel_caseclass_basenameeends_withkebab_casepreg_replace_arraysnake_casestarts_withstr_afterstr_beforestr_containsstr_finishstr_isstr_limitstr_pluralstr_randomstr_replace_arraystr_replace_firststr_replace_laststr_singularstr_slugstr_startstudly_casetitle_casetranstrans_choice
URLs
杂项
abortabort_ifabort_unlessappauthbackbcryptblankbroadcastcacheclass_uses_recursivecollectconfigcookiecsrf_fieldcsrf_tokendddecryptdispatchdispatch_nowdumpencryptenveventfactoryfilledinfologgermethod_fieldnowoldoptionalpolicyredirectreportrequestrescueresolveresponseretrysessiontaptodaythrow_ifthrow_unlesstrait_uses_recursivetransformvalidatorvalueviewwith
方法列表
数组与对象
array_add()
array_add
函数在给定键不存在于数组中时,向数组添加给定的键/值对:
$array = array_add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
array_collapse()
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()
array_divide
函数返回两个数组,一个包含键,另一个包含给定数组的值:
list($keys, $values) = array_divide(['name' => 'Desk']);
// $keys: ['name']
// $values: ['Desk']
array_dot()
array_dot
函数将多维数组展平为单级数组,使用 "点" 符号表示深度:
$array = ['products' => ['desk' => ['price' => 100]]];
$flattened = array_dot($array);
// ['products.desk.price' => 100]
array_except()
array_except
函数从数组中移除给定的键/值对:
$array = ['name' => 'Desk', 'price' => 100];
$filtered = array_except($array, ['price']);
// ['name' => 'Desk']
array_first()
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()
array_flatten
函数将多维数组展平为单级数组:
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$flattened = array_flatten($array);
// ['Joe', 'PHP', 'Ruby']
array_forget()
array_forget
函数使用 "点" 符号从深度嵌套的数组中移除给定的键/值对:
$array = ['products' => ['desk' => ['price' => 100]]];
array_forget($array, 'products.desk');
// ['products' => []]
array_get()
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()
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()
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()
array_only
函数仅返回给定数组中指定的键/值对:
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
$slice = array_only($array, ['name', 'price']);
// ['name' => 'Desk', 'price' => 100]
array_pluck()
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()
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()
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()
array_random
函数从数组中返回一个随机值:
$array = [1, 2, 3, 4, 5];
$random = array_random($array);
// 4 - (随机检索)
您还可以指定要返回的项目数量作为可选的第二个参数。请注意,提供此参数将返回一个数组,即使只需要一个项目:
$items = array_random($array, 2);
// [2, 5] - (随机检索)
array_set()
array_set
函数使用 "点" 符号在深度嵌套的数组中设置值:
$array = ['products' => ['desk' => ['price' => 100]]];
array_set($array, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]
array_sort()
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()
array_sort_recursive
函数使用 sort
函数递归地对数组进行排序:
$array = [
['Roman', 'Taylor', 'Li'],
['PHP', 'Ruby', 'JavaScript'],
];
$sorted = array_sort_recursive($array);
/*
[
['Li', 'Roman', 'Taylor'],
['JavaScript', 'PHP', 'Ruby'],
]
*/
array_where()
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()
array_wrap
函数将给定值包装在数组中。如果给定值已经是数组,则不会更改:
$string = 'Laravel';
$array = array_wrap($string);
// ['Laravel']
如果给定值为 null,将返回一个空数组:
$nothing = null;
$array = array_wrap($nothing);
// []
data_fill()
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()
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()
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()
head
函数返回给定数组中的第一个元素:
$array = [100, 200, 300];
$first = head($array);
// 100
last()
last
函数返回给定数组中的最后一个元素:
$array = [100, 200, 300];
$last = last($array);
// 300
路径
app_path()
app_path
函数返回 app
目录的完全限定路径。您还可以使用 app_path
函数生成相对于应用程序目录的文件的完全限定路径:
$path = app_path();
$path = app_path('Http/Controllers/Controller.php');
base_path()
base_path
函数返回项目根目录的完全限定路径。您还可以使用 base_path
函数生成相对于项目根目录的给定文件的完全限定路径:
$path = base_path();
$path = base_path('vendor/bin');
config_path()
config_path
函数返回 config
目录的完全限定路径。您还可以使用 config_path
函数生成应用程序配置目录中给定文件的完全限定路径:
$path = config_path();
$path = config_path('app.php');
database_path()
database_path
函数返回 database
目录的完全限定路径。您还可以使用 database_path
函数生成数据库目录中给定文件的完全限定路径:
$path = database_path();
$path = database_path('factories/UserFactory.php');
mix()
mix
函数返回 版本化的 Mix 文件 的路径:
$path = mix('css/app.css');
public_path()
public_path
函数返回 public
目录的完全限定路径。您还可以使用 public_path
函数生成公共目录中给定文件的完全限定路径:
$path = public_path();
$path = public_path('css/app.css');
resource_path()
resource_path
函数返回 resources
目录的完全限定路径。您还可以使用 resource_path
函数生成资源目录中给定文件的完全限定路径:
$path = resource_path();
$path = resource_path('assets/sass/app.scss');
storage_path()
storage_path
函数返回 storage
目录的完全限定路径。您还可以使用 storage_path
函数生成存储目录中给定文件的完全限定路径:
$path = storage_path();
$path = storage_path('app/file.txt');
字符串
__()
__
函数使用您的 本地化文件 翻译给定的翻译字符串或翻译键:
echo __('Welcome to our application');
echo __('messages.welcome');
如果指定的翻译字符串或键不存在,__
函数将返回给定值。因此,使用上面的示例,如果翻译键不存在,__
函数将返回 messages.welcome
。
camel_case()
camel_case
函数将给定字符串转换为 camelCase
:
$converted = camel_case('foo_bar');
// fooBar
class_basename()
class_basename
返回给定类的类名,并去除类的命名空间:
$class = class_basename('Foo\Bar\Baz');
// Baz
e()
e
函数运行 PHP 的 htmlspecialchars
函数,并将 double_encode
选项设置为 false
:
echo e('<html>foo</html>');
// <html>foo</html>
ends_with()
ends_with
函数确定给定字符串是否以给定值结尾:
$result = ends_with('This is my name', 'name');
// true
kebab_case()
kebab_case
函数将给定字符串转换为 kebab-case
:
$converted = kebab_case('fooBar');
// foo-bar
preg_replace_array()
preg_replace_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
函数将给定字符串转换为 snake_case
:
$converted = snake_case('fooBar');
// foo_bar
starts_with()
starts_with
函数确定给定字符串是否以给定值开头:
$result = starts_with('This is my name', 'This');
// true
str_after()
str_after
函数返回字符串中给定值之后的所有内容:
$slice = str_after('This is my name', 'This is');
// ' my name'
str_before()
str_before
函数返回字符串中给定值之前的所有内容:
$slice = str_before('This is my name', 'my name');
// 'This is '
str_contains()
str_contains
函数确定给定字符串是否包含给定值(区分大小写):
$contains = str_contains('This is my name', 'my');
// true
您还可以传递一个值数组,以确定给定字符串是否包含任何值:
$contains = str_contains('This is my name', ['my', 'foo']);
// true
str_finish()
str_finish
函数在字符串末尾添加给定值的单个实例,如果它尚未以该值结尾:
$adjusted = str_finish('this/string', '/');
// this/string/
$adjusted = str_finish('this/string/', '/');
// this/string/
str_is()
str_is
函数确定给定字符串是否与给定模式匹配。星号可用于指示通配符:
$matches = str_is('foo*', 'foobar');
// true
$matches = str_is('baz*', 'foobar');
// false
str_limit()
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_plural()
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()
str_random
函数生成指定长度的随机字符串。此函数使用 PHP 的 random_bytes
函数:
$random = str_random(40);
str_replace_array()
str_replace_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
函数替换字符串中给定值的第一个实例:
$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
函数替换字符串中给定值的最后一个实例:
$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
函数将字符串转换为其单数形式。此函数目前仅支持英语:
$singular = str_singular('cars');
// car
$singular = str_singular('children');
// child
str_slug()
str_slug
函数从给定字符串生成 URL 友好的 "slug":
$slug = str_slug('Laravel 5 Framework', '-');
// laravel-5-framework
str_start()
str_start
函数在字符串开头添加给定值的单个实例,如果它尚未以该值开头:
$adjusted = str_start('this/string', '/');
// /this/string
$adjusted = str_start('/this/string/', '/');
// /this/string
studly_case()
studly_case
函数将给定字符串转换为 StudlyCase
:
$converted = studly_case('foo_bar');
// FooBar
title_case()
title_case
函数将给定字符串转换为 Title Case
:
$converted = title_case('a nice title uses the correct case');
// A Nice Title Uses The Correct Case
trans()
trans
函数使用您的 本地化文件 翻译给定的翻译键:
echo trans('messages.welcome');
如果指定的翻译键不存在,trans
函数将返回给定键。因此,使用上面的示例,如果翻译键不存在,trans
函数将返回 messages.welcome
。
trans_choice()
trans_choice
函数使用屈折翻译给定的翻译键:
echo trans_choice('messages.notifications', $unreadCount);
如果指定的翻译键不存在,trans_choice
函数将返回给定键。因此,使用上面的示例,如果翻译键不存在,trans_choice
函数将返回 messages.notifications
。
URLs
action()
action
函数为给定的控制器操作生成 URL。您无需传递控制器的完整命名空间。相反,传递相对于 App\Http\Controllers
命名空间的控制器类名:
$url = action('HomeController@index');
如果方法接受路由参数,您可以将它们作为方法的第二个参数传递:
$url = action('UserController@profile', ['id' => 1]);
asset()
asset
函数使用请求的当前方案(HTTP 或 HTTPS)为资产生成 URL:
$url = asset('img/photo.jpg');
secure_asset()
secure_asset
函数使用 HTTPS 为资产生成 URL:
$url = secure_asset('img/photo.jpg');
route()
route
函数为给定的命名路由生成 URL:
$url = route('routeName');
如果路由接受参数,您可以将它们作为方法的第二个参数传递:
$url = route('routeName', ['id' => 1]);
默认情况下,route
函数生成绝对 URL。如果您希望生成相对 URL,可以将 false
作为第三个参数传递:
$url = route('routeName', ['id' => 1], false);
secure_url()
secure_url
函数生成给定路径的完全限定 HTTPS URL:
$url = secure_url('user/profile');
$url = secure_url('user/profile', [1]);
url()
url
函数生成给定路径的完全限定 URL:
$url = url('user/profile');
$url = url('user/profile', [1]);
如果未提供路径,将返回 Illuminate\Routing\UrlGenerator
实例:
$current = url()->current();
$full = url()->full();
$previous = url()->previous();
杂项
abort()
abort
函数抛出 HTTP 异常,将由 异常处理程序 渲染:
abort(403);
您还可以提供异常的响应文本和自定义响应头:
abort(403, 'Unauthorized.', $headers);
abort_if()
abort_if
函数在给定布尔表达式计算为 true
时抛出 HTTP 异常:
abort_if(! Auth::user()->isAdmin(), 403);
与 abort
方法一样,您还可以提供异常的响应文本作为第三个参数,并将自定义响应头数组作为第四个参数。
abort_unless()
abort_unless
函数在给定布尔表达式计算为 false
时抛出 HTTP 异常:
abort_unless(Auth::user()->isAdmin(), 403);
与 abort
方法一样,您还可以提供异常的响应文本作为第三个参数,并将自定义响应头数组作为第四个参数。
app()
app
函数返回 服务容器 实例:
$container = app();
您可以传递类或接口名称以从容器中解析它:
$api = app('HelpSpot\API');
auth()
auth
函数返回 认证器 实例。您可以使用它代替 Auth
facade 以方便:
$user = auth()->user();
如果需要,您可以指定要访问的守卫实例:
$user = auth('admin')->user();
back()
back
函数生成到用户先前位置的 重定向 HTTP 响应:
return back($status = 302, $headers = [], $fallback = false);
return back();
bcrypt()
bcrypt
函数使用 Bcrypt 哈希 给定值。您可以将其用作 Hash
facade 的替代:
$password = bcrypt('my-secret-password');
broadcast()
broadcast(new UserRegistered($user));
blank()
blank
函数返回给定值是否为 "空白":
blank('');
blank(' ');
blank(null);
blank(collect());
// true
blank(0);
blank(true);
blank(false);
// false
有关 blank
的反义词,请参见 filled
方法。
cache()
cache
函数可用于从 缓存 中获取值。如果给定键在缓存中不存在,将返回可选的默认值:
$value = cache('key');
$value = cache('key', 'default');
您可以通过将键/值对数组传递给函数来将项目添加到缓存中。您还应传递缓存值应被视为有效的分钟数或持续时间:
cache(['key' => 'value'], 5);
cache(['key' => 'value'], now()->addSeconds(10));
class_uses_recursive()
class_uses_recursive
函数返回类使用的所有特性,包括任何子类使用的特性:
$traits = class_uses_recursive(App\User::class);
collect()
collect
函数从给定值创建 集合 实例:
$collection = collect(['taylor', 'abigail']);
config()
config
函数获取 配置 变量的值。可以使用 "点" 语法访问配置值,其中包括您希望访问的文件名和选项。如果配置选项不存在,可以指定默认值并返回:
$value = config('app.timezone');
$value = config('app.timezone', $default);
您可以通过传递键/值对数组在运行时设置配置变量:
config(['app.debug' => true]);
cookie()
cookie
函数创建一个新的 cookie 实例:
$cookie = cookie('name', 'value', $minutes);
csrf_field()
csrf_field
函数生成一个包含 CSRF 令牌值的 HTML hidden
输入字段。例如,使用 Blade 语法:
{{ csrf_field() }}
csrf_token()
csrf_token
函数检索当前 CSRF 令牌的值:
$token = csrf_token();
dd()
dd
函数转储给定变量并结束脚本执行:
dd($value);
dd($value1, $value2, $value3, ...);
如果您不想在转储变量后停止脚本执行,请使用 dump
函数。
decrypt()
decrypt
函数使用 Laravel 的 加密器 解密给定值:
$decrypted = decrypt($encrypted_value);
dispatch()
dispatch
函数将给定 作业 推送到 Laravel 作业队列:
dispatch(new App\Jobs\SendEmails);
dispatch_now()
dispatch_now
函数立即运行给定 作业 并返回其 handle
方法的值:
$result = dispatch_now(new App\Jobs\SendEmails);
dump()
dump
函数转储给定变量:
dump($value);
dump($value1, $value2, $value3, ...);
如果您想在转储变量后停止执行脚本,请使用 dd
函数。
encrypt()
encrypt
函数使用 Laravel 的 加密器 加密给定值:
$encrypted = encrypt($unencrypted_value);
env()
env
函数检索 环境变量 的值或返回默认值:
$env = env('APP_ENV');
// 如果 APP_ENV 未设置,则返回 'production'...
$env = env('APP_ENV', 'production');
如果您在部署过程中执行 config:cache
命令,您应确保仅在配置文件中调用 env
函数。一旦配置被缓存,.env
文件将不会被加载,所有对 env
函数的调用将返回 null
。
event()
event
函数将给定 事件 派发给其监听器:
event(new UserRegistered($user));
factory()
factory
函数为给定类、名称和数量创建模型工厂构建器。它可以在 测试 或 播种 时使用:
$user = factory(App\User::class)->make();
filled()
filled
函数返回给定值是否不为 "空白":
filled(0);
filled(true);
filled(false);
// true
filled('');
filled(' ');
filled(null);
filled(collect());
// false
有关 filled
的反义词,请参见 blank
方法。
info()
info
函数将信息写入 日志:
info('Some helpful information!');
还可以将上下文数据数组传递给函数:
info('User login attempt failed.', ['id' => $user->id]);
logger()
logger
函数可用于将 debug
级别消息写入 日志:
logger('Debug message');
还可以将上下文数据数组传递给函数:
logger('User has logged in.', ['id' => $user->id]);
如果未传递任何值给函数,将返回 logger 实例:
logger()->error('You are not allowed here.');
method_field()
method_field
函数生成一个包含表单 HTTP 动词伪造值的 HTML hidden
输入字段。例如,使用 Blade 语法:
<form method="POST">
{{ method_field('DELETE') }}
</form>
now()
now
函数为当前时间创建一个新的 Illuminate\Support\Carbon
实例:
$now = now();
old()
$value = old('value');
$value = old('value', 'default');
optional()
optional
函数接受任何参数,并允许您访问该对象的属性或调用方法。如果给定对象为 null
,属性和方法将返回 null
而不是导致错误:
return optional($user->address)->street;
{!! old('name', optional($user)->name) !!}
policy()
policy
方法检索给定类的 策略 实例:
$policy = policy(App\User::class);
redirect()
redirect
函数返回 重定向 HTTP 响应,如果不带参数调用,则返回重定向器实例:
return redirect($to = null, $status = 302, $headers = [], $secure = null);
return redirect('/home');
return redirect()->route('route.name');
report()
report
函数将使用您的异常处理器的 report
方法报告异常:
report($e);
request()
request
函数返回当前的请求实例或获取输入项:
$request = request();
$value = request('key', $default);
rescue()
rescue
函数执行给定的闭包并捕获其执行过程中发生的任何异常。所有被捕获的异常将被发送到您的异常处理器的 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()
resolve
函数使用服务容器将给定的类或接口名称解析为其实例:
$api = resolve('HelpSpot\API');
response()
response
函数创建一个响应实例或获取响应工厂的实例:
return response('Hello World', 200, $headers);
return response()->json(['foo' => 'bar'], 200, $headers);
retry()
retry
函数尝试执行给定的回调,直到达到给定的最大尝试次数。如果回调没有抛出异常,则返回其返回值。如果回调抛出异常,则会自动重试。如果超过最大尝试次数,则抛出异常:
return retry(5, function () {
// 尝试5次,每次间隔100毫秒...
}, 100);
session()
session
函数可用于获取或设置会话值:
$value = session('key');
您可以通过传递键/值对数组来设置值:
session(['chairs' => 7, 'instruments' => 3]);
如果没有传递值给函数,将返回会话存储:
$value = session()->get('key');
session()->put('key', $value);
tap()
tap
函数接受两个参数:任意的 $value
和一个闭包。$value
将被传递给闭包,然后由 tap
函数返回。闭包的返回值无关紧要:
$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()
today
函数为当前日期创建一个新的 Illuminate\Support\Carbon
实例:
$today = today();
throw_if()
throw_if
函数在给定的布尔表达式计算为 true
时抛出给定的异常:
throw_if(! Auth::user()->isAdmin(), AuthorizationException::class);
throw_if(
! Auth::user()->isAdmin(),
AuthorizationException::class,
'您无权访问此页面'
);
throw_unless()
throw_unless
函数在给定的布尔表达式计算为 false
时抛出给定的异常:
throw_unless(Auth::user()->isAdmin(), AuthorizationException::class);
throw_unless(
Auth::user()->isAdmin(),
AuthorizationException::class,
'您无权访问此页面'
);
trait_uses_recursive()
trait_uses_recursive
函数返回一个 trait 使用的所有 trait:
$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);
transform()
transform
函数在给定值不为空白时执行 Closure
并返回 Closure
的结果:
$callback = function ($value) {
return $value * 2;
};
$result = transform(5, $callback);
// 10
一个默认值或 Closure
也可以作为方法的第三个参数传递。如果给定值为空白,则返回此值:
$result = transform(null, $callback, '值为空白');
// 值为空白
validator()
validator
函数使用给定的参数创建一个新的验证器实例。您可以使用它来代替 Validator
facade 以方便使用:
$validator = validator($data, $rules, $messages);
value()
value
函数返回给定的值。然而,如果您传递一个 Closure
给函数,Closure
将被执行,然后返回其结果:
$result = value(true);
// true
$result = value(function () {
return false;
});
// false
view()
view
函数检索一个视图实例:
return view('auth.login');
with()
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