辅助函数

简介

Laravel 包含一些多样化的 PHP 辅助函数函数。许多在 Laravel 自身框架中使用;如果你觉得实用,也可以在你应用当中使用。

可用方法

数组

路径

字符串

网址

其它

方法列表

数组

array_add() {#collection-method .first-collection-method}

如果指定的键不存在于该数组,array_add 函数便会将指定的键值对加到数组中:

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

array_collapse() {#collection-method}

array_collapse 函数将数组的每一个数组折成单个数组:

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

array_divide() {#collection-method}

array_divide 函数返回两个数组,一个包含原本数组的键,另一个包含原本数组的值:

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

array_dot() {#collection-method}

array_dot 函数把多维数组扁平化成一维数组,并用「点」式语法表示深度:

  1. $array = array_dot(['foo' => ['bar' => 'baz']]);
  2. // ['foo.bar' => 'baz'];

array_except() {#collection-method}

array_except 函数从数组移除指定的键值对:

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

array_first() {#collection-method}

array_first 函数返回数组中第一个通过测试的元素:

  1. $array = [100, 200, 300];
  2. $value = array_first($array, function ($key, $value) {
  3. return $value >= 150;
  4. });
  5. // 200

可传递第三个参数作为默认值。当没有任何数值通过测试时将返回该数值:

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

array_flatten() {#collection-method}

array_flatten 函数将多维数组扁平化成一维。

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

array_forget() {#collection-method}

array_forget 函数以「点」式语法从深度嵌套数组中移除指定的键值对:

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

array_get() {#collection-method}

array_get 函数使用「点」式语法从深度嵌套数组中取回指定的值:

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

array_get 函数同样接受默认值,当指定的键找不到时返回:

  1. $value = array_get($array, 'names.john', 'default');

array_has() {#collection-method}

array_has 函数使用「点」式语法检查指定的项目是否存在于数组中:

  1. $array = ['products' => ['desk' => ['price' => 100]]];
  2. $hasDesk = array_has($array, ['products.desk']);
  3. // true

array_only() {#collection-method}

array_only 函数从数组返回指定的键值对:

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

array_pluck() {#collection-method}

array_pluck 函数从数组拉出一列指定的键值对:

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

你也能指定要以什么作为结果列的键值:

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

array_pull() {#collection-method}

array_pull 函数从数组移除并返回指定的键值对:

  1. $array = ['name' => 'Desk', 'price' => 100];
  2. $name = array_pull($array, 'name');
  3. // $name: Desk
  4. // $array: ['price' => 100]

array_set() {#collection-method}

array_set 函数使用「点」式语法在深度嵌套数组中写入值:

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

array_sort() {#collection-method}

array_sort 函数借助指定闭包结果排序数组:

  1. $array = [
  2. ['name' => 'Desk'],
  3. ['name' => 'Chair'],
  4. ];
  5. $array = array_values(array_sort($array, function ($value) {
  6. return $value['name'];
  7. }));
  8. /*
  9. [
  10. ['name' => 'Chair'],
  11. ['name' => 'Desk'],
  12. ]
  13. */

array_sort_recursive() {#collection-method}

array_sort_recursive 函数使用 sort 函数递归排序数组:

  1. $array = [
  2. [
  3. 'Roman',
  4. 'Taylor',
  5. 'Li',
  6. ],
  7. [
  8. 'PHP',
  9. 'Ruby',
  10. 'JavaScript',
  11. ],
  12. ];
  13. $array = array_sort_recursive($array);
  14. /*
  15. [
  16. [
  17. 'Li',
  18. 'Roman',
  19. 'Taylor',
  20. ],
  21. [
  22. 'JavaScript',
  23. 'PHP',
  24. 'Ruby',
  25. ]
  26. ];
  27. */

array_where() {#collection-method}

array_where 函数使用指定的闭包过滤数组:

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

head() {#collection-method}

head 函数返回指定数组的第一个元素:

  1. $array = [100, 200, 300];
  2. $first = head($array);
  3. // 100

last() {#collection-method}

last 函数返回指定数组的最后一个元素:

  1. $array = [100, 200, 300];
  2. $last = last($array);
  3. // 300

路径

app_path() {#collection-method}

app_path 函数获取 app 文件夹的完整路径:

  1. $path = app_path();

你同样可以使用 app_path 函数生成针对指定文件相对于 app 目录的完整路径:

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

base_path() {#collection-method}

base_path 函数获取项目根目录的完整路径:

  1. $path = base_path();

你同样可以使用 base_path 函数生成针对指定文件相对于项目根目录的完整路径:

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

config_path() {#collection-method}

config_path 函数获取应用配置目录的完整路径:

  1. $path = config_path();

database_path() {#collection-method}

database_path 函数获取应用数据库目录的完整路径:

  1. $path = database_path();

elixir() {#collection-method}

elixir 函数获取加上版本号的 Elixir 文件路径:

  1. elixir($file);

public_path() {#collection-method}

public_path 函数获取 public 目录的完整路径:

  1. $path = public_path();

storage_path() {#collection-method}

storage_path 函数获取 storage 目录的完整路径:

  1. $path = storage_path();

你同样可以使用 storage_path 函数生成针对指定文件相对于 storage 目录的完整路径:

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

字符串

camel_case() {#collection-method}

camel_case 函数会将指定的字符串转换成 驼峰式命名

  1. $camel = camel_case('foo_bar');
  2. // fooBar

class_basename() {#collection-method}

class_basename 返回不包含命名空间的类名称:

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

e() {#collection-method}

e 函数对指定字符串运行 htmlentities

  1. echo e('<html>foo</html>');
  2. // &lt;html&gt;foo&lt;/html&gt;

ends_with() {#collection-method}

ends_with 函数判断指定字符串结尾是否为指定内容:

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

snake_case() {#collection-method}

snake_case 函数会将指定的字符串转换成 蛇形命名

  1. $snake = snake_case('fooBar');
  2. // foo_bar

str_limit() {#collection-method}

str_limit 函数限制字符串的字符数量。该函数接受一个字符串作为第一个参数,以及最大字符数量作为第二参数:

  1. $value = str_limit('The PHP framework for web artisans.', 7);
  2. // The PHP...

starts_with() {#collection-method}

starts_with 函数判断字符串开头是否为指定内容:

  1. $value = starts_with('This is my name', 'This');
  2. // true

str_contains() {#collection-method}

str_contains 函数判断指定字符串是否包含指定内容:

  1. $value = str_contains('This is my name', 'my');
  2. // true

str_finish() {#collection-method}

str_finish 函数添加指定内容到字符串结尾:

  1. $string = str_finish('this/string', '/');
  2. // this/string/

str_is() {#collection-method}

str_is 函数判断指定的字符串与指定的格式是否符合。星号可作为通配符使用:

  1. $value = str_is('foo*', 'foobar');
  2. // true
  3. $value = str_is('baz*', 'foobar');
  4. // false

str_plural() {#collection-method}

str_plural 函数转换字符串成复数形。该函数目前仅支持英文:

  1. $plural = str_plural('car');
  2. // cars
  3. $plural = str_plural('child');
  4. // children

你可以提供一个整数作为第二参数,来获取字符串的单数或复数形式:

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

str_random() {#collection-method}

str_random 函数生成指定长度的随机字符串:

  1. $string = str_random(40);

str_singular() {#collection-method}

str_singular 函数转换字符串成单数形式。该函数目前仅支持英文:

  1. $singular = str_singular('cars');
  2. // car

str_slug() {#collection-method}

str_slug 函数从指定字符串生成网址友善的「slug」:

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

studly_case() {#collection-method}

studly_case 函数将指定字符串转换成 首字大写命名

  1. $value = studly_case('foo_bar');
  2. // FooBar

trans() {#collection-method}

trans 函数根据你的 本地化文件 翻译指定的语句:

  1. echo trans('validation.required'):

trans_choice() {#collection-method}

trans_choice 函数根据后缀变化翻译指定的语句:

  1. $value = trans_choice('foo.bar', $count);

网址

action() {#collection-method}

action 函数生成指定控制器行为网址。你不需要输入该控制器的完整命名空间。作为替代,请输入基于 App\Http\Controllers 命名空间的控制器类名称:

  1. $url = action('HomeController@getIndex');

如果该方法支持路由参数,你可以作为第二参数传递:

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

asset() {#collection-method}

根据目前请求的协定(HTTP 或 HTTPS)生成资源文件网址:

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

secure_asset() {#collection-method}

根据 HTTPS 生成资源文件网址:

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

route() {#collection-method}

route 函数生成指定路由名称网址:

  1. $url = route('routeName');

如果该路由接受参数,你可以作为第二参数传递:

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

url() {#collection-method}

url 函数生成指定路径的完整网址:

  1. echo url('user/profile');
  2. echo url('user/profile', [1]);

其它

auth() {#collection-method}

auth 函数返回一个认证器实例。你可以使用它取代 Auth facade:

  1. $user = auth()->user();

back() {#collection-method}

back() 函数生成一个重定向响应让用户回到之前的位置:

  1. return back();

bcrypt() {#collection-method}

bcrypt 函数使用 Bcrypt 哈希指定的数值。你可以使用它替代 Hash facade:

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

collect() {#collection-method}

collect 函数从指定的项目生成 集合 实例:

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

config() {#collection-method}

config 获取设置选项的设置值。设置值可通过「点」式语法读取,其中包含要访问的文件名以及选项名称。可传递一默认值在找不到指定的设置选项时返回该数值:

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

config 辅助函数也可以在运行期间,根据指定的键值对指定设置值:

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

csrf_field() {#collection-method}

csrf_field 函数生成包含 CSRF 令牌内容的 HTML 表单隐藏字段。例如,使用 Blade 语法

  1. {!! csrf_field() !!}

csrf_token() {#collection-method}

csrf_token 函数获取当前 CSRF 令牌的内容:

  1. $token = csrf_token();

dd() {#collection-method}

dd 函数输出指定变量并结束脚本运行:

  1. dd($value);

env() {#collection-method}

env 函数获取环境变量值或返回默认值:

  1. $env = env('APP_ENV');
  2. // 当变量不存在时返回一个默认值...
  3. $env = env('APP_ENV', 'production');

event() {#collection-method}

event 函数配送指定 事件 到所属的侦听器:

  1. event(new UserRegistered($user));

factory() {#collection-method}

factory 函数根据指定类、名称以及总数生成模型工厂构造器(model factory builder)。可用于 测试数据填充

  1. $user = factory(App\User::class)->make();

method_field() {#collection-method}

method_field 函数生成模拟 HTTP 表单动作内容的 HTML 表单隐藏字段。例如,使用 Blade 语法

  1. <form method="POST">
  2. {!! method_field('delete') !!}
  3. </form>

old() {#collection-method}

old 函数 获取 闪存到 session 的旧有输入数值:

$value = old('value');

redirect() {#collection-method}

redirect 函数返回重定向器实例以进行 重定向

return redirect('/home');

request() {#collection-method}

request 函数获取目前的 请求 实例或输入的项目:

$request = request();

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

response() {#collection-method}

response 函数创建一个 响应 实例或获取一个响应工厂(response factory)实例:

return response('Hello World', 200, $headers);

return response()->json(['foo' => 'bar'], 200, $headers);

session() {#collection-method}

session 函数可用于获取或设置单个 session 内容:

$value = session('key');

你可以通过传递键值对给该函数进行内容设置:

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

该函数在没有传递参数时,将返回 session 实例:

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

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

value() {#collection-method}

value 函数返回指定数值。而当你传递一个 闭包 给该函数,该 闭包 将被运行并返回结果:

$value = value(function() { return 'bar'; });

view() {#collection-method}

view 函数获取 视图 实例:

return view('auth.login');

with() {#collection-method}

with 函数返回指定的数值。该函数主要用于链式调用回所保存的 seesion 内容,除此之外不大可能用到:

$value = with(new Foo)->work();

{note} 欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创开源社区。

转载请注明:本文档由 Laravel China 社区 [laravel-china.org] 组织翻译。

文档永久地址: http://d.laravel-china.org