辅助函数
介绍
Laravel 包含多种 "辅助" PHP 函数。许多这些函数被框架本身使用;然而,如果你觉得方便,也可以在自己的应用程序中使用它们。
可用方法
数组
array_addarray_collapsearray_dividearray_dotarray_exceptarray_firstarray_flattenarray_forgetarray_getarray_hasarray_onlyarray_pluckarray_prependarray_pullarray_setarray_sortarray_sort_recursivearray_whereheadlast
路径
字符串
camel_caseclass_basenameeends_withsnake_casestr_limitstarts_withstr_containsstr_finishstr_isstr_pluralstr_randomstr_singularstr_slugstudly_casetranstrans_choice
URL
杂项
authbackbcryptcollectconfigcsrf_fieldcsrf_tokendddispatchenveventfactorymethod_fieldoldredirectrequestresponsesessionvalueviewwith
方法列表
数组
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 = array_dot(['foo' => ['bar' => 'baz']]);
// ['foo.bar' => 'baz'];
array_except()
array_except
函数从数组中移除给定的键/值对:
$array = ['name' => 'Desk', 'price' => 100];
$array = array_except($array, ['price']);
// ['name' => 'Desk']
array_first()
array_first
函数返回通过给定真值测试的数组的第一个元素:
$array = [100, 200, 300];
$value = array_first($array, function ($key, $value) {
return $value >= 150;
});
// 200
可以将默认值作为方法的第三个参数传递。如果没有值通过真值测试,将返回此值:
$value = array_first($array, $callback, $default);
array_flatten()
array_flatten
函数将多维数组展平为单级。
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$array = 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]]];
$value = array_get($array, 'products.desk');
// ['price' => 100]
array_get
函数还接受一个默认值,如果找不到特定键,将返回此值:
$value = array_get($array, 'names.john', 'default');
array_has()
array_has
函数检查给定项是否存在于数组中,使用 "点" 符号:
$array = ['products' => ['desk' => ['price' => 100]]];
$hasDesk = array_has($array, 'products.desk');
// true
array_only()
array_only
函数将仅返回给定数组中指定的键/值对:
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
$array = array_only($array, ['name', 'price']);
// ['name' => 'Desk', 'price' => 100]
array_pluck()
array_pluck
函数将从数组中提取给定的键/值对列表:
$array = [
['developer' => ['id' => 1, 'name' => 'Taylor']],
['developer' => ['id' => 2, 'name' => 'Abigail']],
];
$array = array_pluck($array, 'developer.name');
// ['Taylor', 'Abigail'];
你还可以指定希望如何对结果列表进行键控:
$array = 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');
// $array: ['zero', 'one', 'two', 'three', 'four']
array_pull()
array_pull
函数返回并移除数组中的键/值对:
$array = ['name' => 'Desk', 'price' => 100];
$name = array_pull($array, 'name');
// $name: Desk
// $array: ['price' => 100]
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 = [
['name' => 'Desk'],
['name' => 'Chair'],
];
$array = array_values(array_sort($array, function ($value) {
return $value['name'];
}));
/*
[
['name' => 'Chair'],
['name' => 'Desk'],
]
*/
array_sort_recursive()
array_sort_recursive
函数使用 sort
函数递归地对数组进行排序:
$array = [
[
'Roman',
'Taylor',
'Li',
],
[
'PHP',
'Ruby',
'JavaScript',
],
];
$array = array_sort_recursive($array);
/*
[
[
'Li',
'Roman',
'Taylor',
],
[
'JavaScript',
'PHP',
'Ruby',
]
];
*/
array_where()
array_where
函数使用给定闭包过滤数组:
$array = [100, '200', 300, '400', 500];
$array = array_where($array, function ($key, $value) {
return is_string($value);
});
// [1 => 200, 3 => 400]
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
目录的完全限定路径:
$path = app_path();
你也可以使用 app_path
函数生成相对于应用程序目录的给定文件的完全限定路径:
$path = app_path('Http/Controllers/Controller.php');
base_path()
base_path
函数返回项目根目录的完全限定路径:
$path = base_path();
你也可以使用 base_path
函数生成相对于应用程序目录的给定文件的完全限定路径:
$path = base_path('vendor/bin');
config_path()
config_path
函数返回应用程序配置目录的完全限定路径:
$path = config_path();
database_path()
database_path
函数返回应用程序数据库目录的完全限定路径:
$path = database_path();
elixir()
elixir
函数获取版本化 Elixir 文件的路径:
elixir($file);
public_path()
public_path
函数返回 public
目录的完全限定路径:
$path = public_path();
resource_path()
resource_path
函数返回 resources
目录的完全限定路径:
$path = resource_path();
你也可以使用 resource_path
函数生成相对于存储目录的给定文件的完全限定路径:
$path = resource_path('assets/sass/app.scss');
storage_path()
storage_path
函数返回 storage
目录的完全限定路径:
$path = storage_path();
你也可以使用 storage_path
函数生成相对于存储目录的给定文件的完全限定路径:
$path = storage_path('app/file.txt');
字符串
camel_case()
camel_case
函数将给定字符串转换为 camelCase
:
$camel = camel_case('foo_bar');
// fooBar
class_basename()
class_basename
返回给定类的类名,并去除类的命名空间:
$class = class_basename('Foo\Bar\Baz');
// Baz
e()
e
函数对给定字符串运行 htmlentities
:
echo e('<html>foo</html>');
// <html>foo</html>
ends_with()
ends_with
函数确定给定字符串是否以给定值结尾:
$value = ends_with('This is my name', 'name');
// true
snake_case()
snake_case
函数将给定字符串转换为 snake_case
:
$snake = snake_case('fooBar');
// foo_bar
str_limit()
str_limit
函数限制字符串中的字符数。该函数接受一个字符串作为第一个参数,最大字符数作为第二个参数:
$value = str_limit('The PHP framework for web artisans.', 7);
// The PHP...
starts_with()
starts_with
函数确定给定字符串是否以给定值开头:
$value = starts_with('This is my name', 'This');
// true
str_contains()
str_contains
函数确定给定字符串是否包含给定值:
$value = str_contains('This is my name', 'my');
// true
str_finish()
str_finish
函数向字符串添加给定值的单个实例:
$string = str_finish('this/string', '/');
// this/string/
str_is()
str_is
函数确定给定字符串是否与给定模式匹配。星号可用于指示通配符:
$value = str_is('foo*', 'foobar');
// true
$value = str_is('baz*', 'foobar');
// false
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
函数生成指定长度的随机字符串:
$string = str_random(40);
str_singular()
str_singular
函数将字符串转换为其单数形式。此函数目前仅支持英语:
$singular = str_singular('cars');
// car
str_slug()
str_slug
函数从给定字符串生成 URL 友好的 "slug":
$title = str_slug('Laravel 5 Framework', '-');
// laravel-5-framework
studly_case()
studly_case
函数将给定字符串转换为 StudlyCase
:
$value = studly_case('foo_bar');
// FooBar
trans()
trans
函数使用你的 本地化文件 翻译给定的语言行:
echo trans('validation.required'):
trans_choice()
trans_choice
函数使用屈折翻译给定的语言行:
$value = trans_choice('foo.bar', $count);
URL
action()
action
函数为给定的控制器操作生成 URL。你不需要传递控制器的完整命名空间。相反,传递相对于 App\Http\Controllers
命名空间的控制器类名:
$url = action('HomeController@getIndex');
如果方法接受路由参数,你可以将它们作为方法的第二个参数传递:
$url = action('UserController@profile', ['id' => 1]);
asset()
使用请求的当前方案(HTTP 或 HTTPS)为资产生成 URL:
$url = asset('img/photo.jpg');
secure_asset()
使用 HTTPS 为资产生成 URL:
echo secure_asset('foo/bar.zip', $title, $attributes = []);
route()
route
函数为给定的命名路由生成 URL:
$url = route('routeName');
如果路由接受参数,你可以将它们作为方法的第二个参数传递:
$url = route('routeName', ['id' => 1]);
url()
url
函数生成到给定路径的完全限定 URL:
echo url('user/profile');
echo url('user/profile', [1]);
如果未提供路径,将返回 Illuminate\Routing\UrlGenerator
实例:
echo url()->current();
echo url()->full();
echo url()->previous();
杂项
auth()
auth
函数返回一个认证器实例。你可以使用它来代替 Auth
facade 以方便:
$user = auth()->user();
back()
back()
函数生成重定向响应到用户的上一个位置:
return back();
bcrypt()
bcrypt
函数使用 Bcrypt 哈希给定值。你可以将其用作 Hash
facade 的替代品:
$password = bcrypt('my-secret-password');
collect()
collect
函数从提供的项目创建一个 集合 实例:
$collection = collect(['taylor', 'abigail']);
config()
config
函数获取配置变量的值。配置值可以使用 "点" 语法访问,其中包括文件名和你希望访问的选项。可以指定默认值,如果配置选项不存在,将返回此值:
$value = config('app.timezone');
$value = config('app.timezone', $default);
config
辅助函数还可以通过传递键/值对数组在运行时设置配置变量:
config(['app.debug' => true]);
csrf_field()
csrf_field
函数生成一个包含 CSRF 令牌值的 HTML hidden
输入字段。例如,使用 Blade 语法:
{{ csrf_field() }}
csrf_token()
csrf_token
函数检索当前 CSRF 令牌的值:
$token = csrf_token();
dd()
dd
函数转储给定变量并结束脚本执行:
dd($value);
如果你不想停止脚本的执行,请改用 dump
函数:
dump($value);
dispatch()
dispatch
函数将新作业推送到 Laravel 作业队列:
dispatch(new App\Jobs\SendEmails);
env()
env
函数获取环境变量的值或返回默认值:
$env = env('APP_ENV');
// 如果变量不存在,返回默认值...
$env = env('APP_ENV', 'production');
event()
event
函数将给定 事件 派发给其监听器:
event(new UserRegistered($user));
factory()
factory
函数为给定类、名称和数量创建模型工厂构建器。它可以在 测试 或 播种 时使用:
$user = factory(App\User::class)->make();
method_field()
method_field
函数生成一个包含表单 HTTP 动词伪造值的 HTML hidden
输入字段。例如,使用 Blade 语法:
<form method="POST">
{{ method_field('DELETE') }}
</form>
old()
old
函数 检索 闪存到会话中的旧输入值:
$value = old('value');
$value = old('value', 'default');
redirect()
redirect
函数返回一个重定向器实例以进行 重定向:
return redirect('/home');
request()
request
函数返回当前 请求 实例或获取输入项:
$request = request();
$value = request('key', $default = null)
response()
response
函数创建一个 响应 实例或获取响应工厂的实例:
return response('Hello World', 200, $headers);
return response()->json(['foo' => 'bar'], 200, $headers);
session()
session
函数可用于获取/设置会话值:
$value = session('key');
你可以通过传递键/值对数组来设置值:
session(['chairs' => 7, 'instruments' => 3]);
如果没有传递值给函数,将返回会话存储:
$value = session()->get('key');
session()->put('key', $value);
value()
value
函数的行为将简单地返回给定的值。然而,如果你传递一个 Closure
给函数,Closure
将被执行,然后返回其结果:
$value = value(function() { return 'bar'; });
view()
view
函数检索一个 视图 实例:
return view('auth.login');
with()
with
函数返回给定的值。此函数主要用于方法链,在其他情况下无法实现:
$value = with(new Foo)->work();