辅助函数

未匹配的标注
本文档最新版为 10.x,旧版本可能放弃维护,推荐阅读最新版!

辅助函数

简介

Laravel 包含各种各样的全局 PHP 「辅助」函数,框架本身也大量的使用了这些功能函数;如果你觉得方便,你可以在你的应用中任意使用这些函数。

可用方法

数组 & 对象

路径

字符串

流畅的字符串

URLs

其他

方法列表

数组 & 对象

Arr::accessible() {#collection-method .first-collection-method}

Arr::accessible 函数检查给定的值是否可数组式访问:

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;

$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);

// true

$isAccessible = Arr::accessible(new Collection);

// true

$isAccessible = Arr::accessible('abc');

// false

$isAccessible = Arr::accessible(new stdClass);

// false

Arr::add() {#collection-method}

如果给定的键在数组中不存在或给定的键的值被设置为 null ,那么 Arr::add 函数将会把给定的键值对添加到数组中:

use Illuminate\Support\Arr;

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

// ['name' => 'Desk', 'price' => 100]

$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);

// ['name' => 'Desk', 'price' => 100]

Arr::collapse() {#collection-method}

Arr::collapse 函数将多个数组合并为一个数组:

use Illuminate\Support\Arr;

$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

// [1, 2, 3, 4, 5, 6, 7, 8, 9]

Arr::crossJoin() {#collection-method}

Arr::crossJoin 函数交叉连接给定的数组,返回具有所有可能排列的笛卡尔乘积:

use Illuminate\Support\Arr;

$matrix = Arr::crossJoin([1, 2], ['a', 'b']);

/*
    [
        [1, 'a'],
        [1, 'b'],
        [2, 'a'],
        [2, 'b'],
    ]
*/

$matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']);

/*
    [
        [1, 'a', 'I'],
        [1, 'a', 'II'],
        [1, 'b', 'I'],
        [1, 'b', 'II'],
        [2, 'a', 'I'],
        [2, 'a', 'II'],
        [2, 'b', 'I'],
        [2, 'b', 'II'],
    ]
*/

Arr::divide() {#collection-method}

Arr::divide 函数返回一个二维数组,一个值包含原数组的键,另一个值包含原数组的值:

use Illuminate\Support\Arr;

[$keys, $values] = Arr::divide(['name' => 'Desk']);

// $keys: ['name']

// $values: ['Desk']

Arr::dot() {#collection-method}

Arr::dot 函数将多维数组中所有的键平铺到一维数组中,新数组使用「.」符号表示层级包含关系:

use Illuminate\Support\Arr;

$array = ['products' => ['desk' => ['price' => 100]]];

$flattened = Arr::dot($array);

// ['products.desk.price' => 100]

Arr::except() {#collection-method}

Arr::except 函数从数组中删除指定的键值对:

use Illuminate\Support\Arr;

$array = ['name' => 'Desk', 'price' => 100];

$filtered = Arr::except($array, ['price']);

// ['name' => 'Desk']

Arr::exists() {#collection-method}

Arr::exists 检查给定的键是否存在提供的数组中:

use Illuminate\Support\Arr;

$array = ['name' => 'John Doe', 'age' => 17];

$exists = Arr::exists($array, 'name');

// true

$exists = Arr::exists($array, 'salary');

// false

Arr::first() {#collection-method}

Arr::first 函数返回数组中满足指定条件的第一个元素:

use Illuminate\Support\Arr;

$array = [100, 200, 300];

$first = Arr::first($array, function ($value, $key) {
    return $value >= 150;
});

// 200

将默认值作为第三个参数传递给该方法,如果没有值满足条件,则返回该默认值:

use Illuminate\Support\Arr;

$first = Arr::first($array, $callback, $default);

Arr::flatten() {#collection-method}

Arr::flatten 函数将多维数组中数组的值取出平铺为一维数组:

use Illuminate\Support\Arr;

$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];

$flattened = Arr::flatten($array);

// ['Joe', 'PHP', 'Ruby']

Arr::forget() {#collection-method}

Arr::forget 函数使用「.」符号从深度嵌套的数组中删除给定的键值对:

use Illuminate\Support\Arr;

$array = ['products' => ['desk' => ['price' => 100]]];

Arr::forget($array, 'products.desk');

// ['products' => []]

Arr::get() {#collection-method}

Arr::get 函数使用「.」符号从深度嵌套的数组根据指定键检索值:

use Illuminate\Support\Arr;

$array = ['products' => ['desk' => ['price' => 100]]];

$price = Arr::get($array, 'products.desk.price');

// 100

Arr::get 函数也可以接受一个默认值,如果没有找到特定的键,将返回默认值:

use Illuminate\Support\Arr;

$discount = Arr::get($array, 'products.desk.discount', 0);

// 0

Arr::has() {#collection-method}

Arr::has 函数使用「.」符号判断数组中是否存在指定的一个或多个键:

use Illuminate\Support\Arr;

$array = ['product' => ['name' => 'Desk', 'price' => 100]];

$contains = Arr::has($array, 'product.name');

// true

$contains = Arr::has($array, ['product.price', 'product.discount']);

// false

Arr::hasAny() {#collection-method}

Arr::hasAny 函数使用「.」符号判断数组中是否存在给定集合中的任一值作为键:

use Illuminate\Support\Arr;

$array = ['product' => ['name' => 'Desk', 'price' => 100]];

$contains = Arr::hasAny($array, 'product.name');

// true

$contains = Arr::hasAny($array, ['product.name', 'product.discount']);

// true

$contains = Arr::hasAny($array, ['category', 'product.discount']);

// false

Arr::isAssoc() {#collection-method}

如果给定数组是关联数组,则 Arr::isAssoc 函数返回 true ,如果数组没有以零开头的连续数字键,则将其视为「关联」:

use Illuminate\Support\Arr;

$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);

// true

$isAssoc = Arr::isAssoc([1, 2, 3]);

// false

Arr::last() {#collection-method}

Arr::last 函数返回数组中满足指定条件的最后一个元素:

use Illuminate\Support\Arr;

$array = [100, 200, 300, 110];

$last = Arr::last($array, function ($value, $key) {
    return $value >= 150;
});

// 300

将默认值作为第三个参数传递给该方法,如果没有值满足条件,则返回该默认值:

use Illuminate\Support\Arr;

$last = Arr::last($array, $callback, $default);

Arr::only() {#collection-method}

Arr::only 函数只返回给定数组中指定的键值对:

use Illuminate\Support\Arr;

$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];

$slice = Arr::only($array, ['name', 'price']);

// ['name' => 'Desk', 'price' => 100]

Arr::pluck() {#collection-method}

Arr::pluck 函数从数组中检索给定键的所有值:

use Illuminate\Support\Arr;

$array = [
    ['developer' => ['id' => 1, 'name' => 'Taylor']],
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
];

$names = Arr::pluck($array, 'developer.name');

// ['Taylor', 'Abigail']

你也可以指定结果的键:

use Illuminate\Support\Arr;

$names = Arr::pluck($array, 'developer.name', 'developer.id');

// [1 => 'Taylor', 2 => 'Abigail']

Arr::prepend() {#collection-method}

Arr::prepend 函数将一个值插入到数组的开始位置:

use Illuminate\Support\Arr;

$array = ['one', 'two', 'three', 'four'];

$array = Arr::prepend($array, 'zero');

// ['zero', 'one', 'two', 'three', 'four']

你也可以指定插入值的键:

use Illuminate\Support\Arr;

$array = ['price' => 100];

$array = Arr::prepend($array, 'Desk', 'name');

// ['name' => 'Desk', 'price' => 100]

Arr::pull() {#collection-method}

Arr::pull 函数从数组中返回指定键的值并删除此键值对:

use Illuminate\Support\Arr;

$array = ['name' => 'Desk', 'price' => 100];

$name = Arr::pull($array, 'name');

// $name: Desk

// $array: ['price' => 100]

默认值可以作为第三个参数传递给该方法,如果键不存在,则返回该值:

use Illuminate\Support\Arr;

$value = Arr::pull($array, $key, $default);

Arr::query() {#collection-method}

Arr::query 函数将数组转换为查询字符串:

use Illuminate\Support\Arr;

$array = [
    'name' => 'Taylor',
    'order' => [
        'column' => 'created_at',
        'direction' => 'desc'
    ]
];

Arr::query($array);

// name=Taylor&order[column]=created_at&order[direction]=desc

Arr::random() {#collection-method}

Arr::random 函数从数组中随机返回一个值:

use Illuminate\Support\Arr;

$array = [1, 2, 3, 4, 5];

$random = Arr::random($array);

// 4 - (retrieved randomly)

你也可以将返回值的数量作为可选的第二个参数传递给该方法,请注意,提供这个参数会返回一个数组,即使是你只需要一项:

use Illuminate\Support\Arr;

$items = Arr::random($array, 2);

// [2, 5] - (retrieved randomly)

Arr::set() {#collection-method}

Arr::set 函数使用「.」符号在多维数组中设置指定键的值:

use Illuminate\Support\Arr;

$array = ['products' => ['desk' => ['price' => 100]]];

Arr::set($array, 'products.desk.price', 200);

// ['products' => ['desk' => ['price' => 200]]]

Arr::shuffle() {#collection-method}

Arr::shuffle 函数将数组中值进行随机排序:

use Illuminate\Support\Arr;

$array = Arr::shuffle([1, 2, 3, 4, 5]);

// [3, 2, 5, 1, 4] - (generated randomly)

Arr::sort() {#collection-method}

Arr::sort 函数根据数组的值大小进行排序:

use Illuminate\Support\Arr;

$array = ['Desk', 'Table', 'Chair'];

$sorted = Arr::sort($array);

// ['Chair', 'Desk', 'Table']

你也可以根据给定回调函数返回的结果对数组进行排序:

use Illuminate\Support\Arr;

$array = [
    ['name' => 'Desk'],
    ['name' => 'Table'],
    ['name' => 'Chair'],
];

$sorted = array_values(Arr::sort($array, function ($value) {
    return $value['name'];
}));

/*
    [
        ['name' => 'Chair'],
        ['name' => 'Desk'],
        ['name' => 'Table'],
    ]
*/

Arr::sortRecursive() {#collection-method}

Arr::sortRecursive 函数使用 sort 函数对数值子数组进行递归排序,使用 ksort 函数对关联子数组进行递归排序:

use Illuminate\Support\Arr;

$array = [
    ['Roman', 'Taylor', 'Li'],
    ['PHP', 'Ruby', 'JavaScript'],
    ['one' => 1, 'two' => 2, 'three' => 3],
];

$sorted = Arr::sortRecursive($array);

/*
    [
        ['JavaScript', 'PHP', 'Ruby'],
        ['one' => 1, 'three' => 3, 'two' => 2],
        ['Li', 'Roman', 'Taylor'],
    ]
*/

Arr::where() {#collection-method}

Arr::where 函数使用给定的回调函数返回的结果过滤数组:

use Illuminate\Support\Arr;

$array = [100, '200', 300, '400', 500];

$filtered = Arr::where($array, function ($value, $key) {
    return is_string($value);
});

// [1 => '200', 3 => '400']

Arr::wrap() {#collection-method}

Arr::wrap 函数可以将给定值转换为一个数组:

use Illuminate\Support\Arr;

$string = 'Laravel';

$array = Arr::wrap($string);

// ['Laravel']

如果给定值是 null ,将返回一个空数组:

use Illuminate\Support\Arr;

$array = Arr::wrap(null);

// []

如果给定值已经是一个数组,将不会被转换

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

函数也接受一个默认值,如果没有找到指定的键,将返回默认值:

$discount = data_get($data, 'products.desk.discount', 0);

// 0

该函数还接受「*」作为通配符,来指向数组或对象的任何键:

$data = [
    'product-one' => ['name' => 'Desk 1', 'price' => 100],
    'product-two' => ['name' => 'Desk 2', 'price' => 150],
];

data_get($data, '*.name');

// ['Desk 1', 'Desk 2'];

data_set() {#collection-method}

data_set 函数使用「.」符号从多维数组或对象中根据指定键设置值:

$data = ['products' => ['desk' => ['price' => 100]]];

data_set($data, 'products.desk.price', 200);

// ['products' => ['desk' => ['price' => 200]]]

data_get一样, 函数也支持使用「*」 作为通配符给相应键名赋值:

$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, $overwrite = 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 函数来生成应用目录下特定文件的完整路径:

$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 函数来生成应用配置目录中的特定文件的完整路径:

$path = config_path();

$path = config_path('app.php');

database_path() {#collection-method}

database_path函数返回 database 目录的完整路径。也可以使用 database_path 函数来生成数据库目录下特定文件的完整路径:

$path = database_path();

$path = database_path('factories/UserFactory.php');

mix() {#collection-method}

mix函数返回 编译前端资源(Mix)的路径,便于加载css,js等静态文件:

$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('sass/app.scss');

storage_path() {#collection-method}

storage_path 函数返回 storage 目录的完整路径。 你也可以用storage_path 函数来生成位于资源路径中的特定文件路径:
$path = storage_path();

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

字符串函数

__() {#collection-method}

__ 函数可使用 本地化文件 来翻译指定的字符串或特定的key:

echo __('Welcome to our application');

echo __('messages.welcome');

如果给定翻译的字符串或者key不存在, 则 __ 会返回你指定的值. 所以上述例子中, 如果给定翻译的字符串或者key不存在,则 __ 函数会返回messages.welcome

class_basename() {#collection-method}

class_basename 函数返回不带命名空间的特定类的类名:

$class = class_basename('Foo\Bar\Baz');

// Baz

e() {#collection-method}

e 函数运行PHP的htmlspecialchars 函数,且 double_encode 默认设定为 true

echo e('<html>foo</html>');

// &lt;html&gt;foo&lt;/html&gt;

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

// The event will take place between 8:30 and 9:00

Str::after() {#collection-method}

Str::after 方法返回字符串中指定值之后的所有内容。如果字符串中不存在这个值,它将返回整个字符串:

use Illuminate\Support\Str;

$slice = Str::after('This is my name', 'This is');

// ' my name'

Str::afterLast() {#collection-method}

Str::afterLast 方法返回字符串中指定值最后一次出现后的所有内容。如果字符串中不存在这个值,它将返回整个字符串:

use Illuminate\Support\Str;

$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');

// 'Controller'

Str::ascii() {#collection-method}

Str::ascii 方法尝试将字符串转换为 ASCII 值:

use Illuminate\Support\Str;

$slice = Str::ascii('û');

// 'u'

Str::before() {#collection-method}

Str::before 方法返回字符串中指定值之前的所有内容:

use Illuminate\Support\Str;

$slice = Str::before('This is my name', 'my name');

// 'This is '

Str::beforeLast() {#collection-method}

Str::beforeLast 方法返回字符串中指定值最后一次出现前的所有内容:

use Illuminate\Support\Str;

$slice = Str::beforeLast('This is my name', 'is');

// 'This '

Str::between() {#collection-method}

Str::between 方法返回字符串在指定两个值之间的内容:

use Illuminate\Support\Str;

$slice = Str::between('This is my name', 'This', 'name');

// ' is my '

Str::camel() {#collection-method}

Str::camel 方法将指定字符串转换为 驼峰式 表示方法:

use Illuminate\Support\Str;

$converted = Str::camel('foo_bar');

// fooBar

Str::contains() {#collection-method}

Str::contains 方法判断指定字符串中是否包含另一指定字符串(区分大小写):

use Illuminate\Support\Str;

$contains = Str::contains('This is my name', 'my');

// true

你亦可以传递数组的值的形式来判断指定字符串是否包含数组中的任一值:

use Illuminate\Support\Str;

$contains = Str::contains('This is my name', ['my', 'foo']);

// true

Str::containsAll() {#collection-method}

Str::containsAll 方法用于判断指定字符串是否包含指定数组中的所有值:

use Illuminate\Support\Str;

$containsAll = Str::containsAll('This is my name', ['my', 'name']);

// true

Str::endsWith() {#collection-method}

Str::endsWith 方法用于判断指定字符串是否以另一指定字符串结尾:

use Illuminate\Support\Str;

$result = Str::endsWith('This is my name', 'name');

// true

你亦可以传递数组的值的形式来判断指定字符串是否包含指定数组中的任一值:

use Illuminate\Support\Str;

$result = Str::endsWith('This is my name', ['name', 'foo']);

// true

$result = Str::endsWith('This is my name', ['this', 'foo']);

// false

Str::finish() {#collection-method}

Str::finish 方法将指定的字符串修改为以指定的值结尾的形式:

use Illuminate\Support\Str;

$adjusted = Str::finish('this/string', '/');

// this/string/

$adjusted = Str::finish('this/string/', '/');

// this/string/

Str::is() {#collection-method}

Str::is 方法用来判断字符串是否与指定模式匹配。星号 * 可用于表示通配符:

use Illuminate\Support\Str;

$matches = Str::is('foo*', 'foobar');

// true

$matches = Str::is('baz*', 'foobar');

// false

Str::isAscii() {#collection-method}

Str::isAscii 方法用于判断字符串是否是 7 位 ASCII:

use Illuminate\Support\Str;

$isAscii = Str::isAscii('Taylor');

// true

$isAscii = Str::isAscii('ü');

// false

Str::isUuid() {#collection-method}

Str::isUuid 方法用于判断指定字符串是否是有效的 UUID :

use Illuminate\Support\Str;

$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');

// true

$isUuid = Str::isUuid('laravel');

// false

Str::kebab() {#collection-method}

Str::kebab 方法将字符串转换为 烤串式( kebab-case ) 表示方法:

use Illuminate\Support\Str;

$converted = Str::kebab('fooBar');

// foo-bar

Str::length() {#collection-method}

Str::length 方法返回指定字符串的长度:

use Illuminate\Support\Str;

$length = Str::length('Laravel');

// 7

Str::limit() {#collection-method}

Str::limit 方法将字符串以指定长度进行截断:

use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);

// The quick brown fox...

你也可通过第三个参数来改变追加到末尾的字符串:

use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');

// The quick brown fox (...)

Str::lower() {#collection-method}

Str::lower 方法用于将字符串转换为小写:

use Illuminate\Support\Str;

$converted = Str::lower('LARAVEL');

// laravel

Str::markdown() {#collection-method}

Str::markdown 方法可以将GitHub风格的Markdown转换为HTML

use Illuminate\Support\Str;

$html = Str::markdown('# Laravel');

// <h1>Laravel</h1>

$html = Str::markdown('# Taylor <b>Otwell</b>', [
    'html_input' => 'strip',
]);

// <h1>Taylor Otwell</h1>

Str::orderedUuid() {#collection-method}

Str::orderedUuid 方法用于生成一个「时间戳优先」的 UUID ,它可作为数据库索引列的有效值:

use Illuminate\Support\Str;

return (string) Str::orderedUuid();

Str::padBoth() {#collection-method}

Str::padBoth 方法包装了 PHP 的 str_pad 函数,在指定字符串的两侧填充上另一字符串:

use Illuminate\Support\Str;

$padded = Str::padBoth('James', 10, '_');

// '__James___'

$padded = Str::padBoth('James', 10);

// '  James   '

Str::padLeft() {#collection-method}

Str::padLeft 方法包装了 PHP 的 str_pad 函数,在指定字符串的左侧填充上另一字符串:

use Illuminate\Support\Str;

$padded = Str::padLeft('James', 10, '-=');

// '-=-=-James'

$padded = Str::padLeft('James', 10);

// '     James'

Str::padRight() {#collection-method}

Str::padRight 方法包装了 PHP 的 str_pad 函数,在指定字符串的右侧填充上另一字符串:

use Illuminate\Support\Str;

$padded = Str::padRight('James', 10, '-');

// 'James-----'

$padded = Str::padRight('James', 10);

// 'James     '

Str::plural() {#collection-method}

Str::plural 方法将单数形式的字符串转换为复数形式。目前该函数仅支持英语:

use Illuminate\Support\Str;

$plural = Str::plural('car');

// cars

$plural = Str::plural('child');

// children

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

use Illuminate\Support\Str;

$plural = Str::plural('child', 2);

// children

$singular = Str::plural('child', 1);

// child

Str::pluralStudly() {#collection-method}

Str::pluralStudly 方法将以驼峰格式的单数字符串转化为其复数形式。目前该函数仅支持英语:

use Illuminate\Support\Str;

$plural = Str::pluralStudly('VerifiedHuman');

// VerifiedHumans

$plural = Str::pluralStudly('UserFeedback');

// UserFeedback

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

use Illuminate\Support\Str;

$plural = Str::pluralStudly('VerifiedHuman', 2);

// VerifiedHumans

$singular = Str::pluralStudly('VerifiedHuman', 1);

// VerifiedHuman

Str::random() {#collection-method}

Str::random 方法用于生成指定长度的随机字符串。这个函数使用了PHP的 random_bytes 函数:

use Illuminate\Support\Str;

$random = Str::random(40);

Str::replaceArray() {#collection-method}

Str::replaceArray 方法使用数组有序的替换字符串中的特定字符:

use Illuminate\Support\Str;

$string = 'The event will take place between ? and ?';

$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);

// 活动将在 8:30 到 9:00 之间举行

Str::replaceFirst() {#collection-method}

Str::replaceFirst 函数替换字符串中给定值的第一个匹配项 :

use Illuminate\Support\Str;

$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');

// a quick brown fox jumps over the lazy dog

Str::replaceLast() {#collection-method}

Str::replaceLast 函数替换字符串中最后一次出现的给定值:

use Illuminate\Support\Str;

$replaced = Str::replaceLast('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 函数将字符串转换为单数形式。该函数目前仅支持英文:

use Illuminate\Support\Str;

$singular = Str::singular('cars');

// car

$singular = Str::singular('children');

// child

Str::slug() {#collection-method}

Str::slug 函数将给定的字符串生成一个 URL 友好的「slug」:

use Illuminate\Support\Str;

$slug = Str::slug('Laravel 5 Framework', '-');

// laravel-5-framework

Str::snake() {#collection-method}

Str::snake 方法是将驼峰的函数名或者字符串转换成 _ 命名的函数或者字符串,例如 snakeCase 转换成 snake_case

use Illuminate\Support\Str;

$converted = Str::snake('fooBar');

// foo_bar

Str::start() {#collection-method}

Str::start 方法是将给定的值添加到字符串的开始位置,例如:

use Illuminate\Support\Str;

$adjusted = Str::start('this/string', '/');

// /this/string

$adjusted = Str::start('/this/string', '/');

// /this/string

Str::startsWith() {#collection-method}

Str::startsWith 方法用来判断给定的字符串是否为给定值的开头:

use Illuminate\Support\Str;

$result = Str::startsWith('This is my name', 'This');

// true

Str::studly() {#collection-method}

Str::studly 方法将给定的字符串转换为 驼峰命名 的字符串:

use Illuminate\Support\Str;

$converted = Str::studly('foo_bar');

// FooBar

Str::substr() {#collection-method}

Str::substr 方法与php自带的字符串 stustr 截取函数相同:

use Illuminate\Support\Str;

$converted = Str::substr('The Laravel Framework', 4, 7);

// Laravel

Str::substrCount() {#collection-method}

Str::substrCount 方法返回给定字符串中给定值出现的次数:

use Illuminate\Support\Str;

$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');

// 2

Str::title() {#collection-method}

Str::title 方法是把指定的字符串,每个单词首字母大写:

use Illuminate\Support\Str;

$converted = Str::title('a nice title uses the correct case');

// A Nice Title Uses The Correct Case

Str::ucfirst() {#collection-method}

Str::ucfirst 方法是把指定的字符串首字母大写:

use Illuminate\Support\Str;

$string = Str::ucfirst('foo bar');

// Foo bar

Str::upper() {#collection-method}

Str::upper 函数用于将指定字符串转换为大写:

use Illuminate\Support\Str;

$string = Str::upper('laravel');

// LARAVEL

Str::uuid() {#collection-method}

Str::uuid 方法用于生成一个 UUID (第 4 版):

use Illuminate\Support\Str;

return (string) Str::uuid();

Str::words() {#collection-method}

Str::words 方法用于限制字符串中的单词数。 可以通过它的第三个参数将另一个字符串传递给此方法,以指定应将哪个字符串附加到截断的字符串的末尾:

use Illuminate\Support\Str;

return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');

// Perfectly balanced, as >>>

trans() {#collection-method}

The trans 函数使用您的 本地化文件 翻译给定键:

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

流畅的字符串函数

流畅字符串(Fluent strings)提供了一种更流畅的、拥有面向对象接口形式的字符串,它允许使用比传统字符串操作更具可读性的语法来进行多字符串的链式操作。

after {#collection-method}

after 方法将返回字符串中指定值后的所有内容。如果字符串中不存在这个值,它将返回整个字符串:

use Illuminate\Support\Str;

$slice = Str::of('This is my name')->after('This is');

// ' my name'

afterLast {#collection-method}

afterLast方法返回字符串中指定值最后一次出现后的所有内容。如果字符串中不存在这个值,它将返回整个字符串:

use Illuminate\Support\Str;

$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');

// 'Controller'

append {#collection-method}

append方法为字符串附加上指定的值:

use Illuminate\Support\Str;

$string = Str::of('Taylor')->append(' Otwell');

// 'Taylor Otwell'

ascii {#collection-method}

ascii方法尝试将字符串转换为 ASCII 值:

use Illuminate\Support\Str;

$string = Str::of('ü')->ascii();

// 'u'

basename {#collection-method}

basename方法将返回指定字符串的结尾部分:

use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz')->basename();

// 'baz'

如果有必要,您亦可提供提供一个「扩展名」,将从尾部的组件中移除它。

use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');

// 'baz'

before {#collection-method}

before方法返回字符串中指定值之前的所有内容:

use Illuminate\Support\Str;

$slice = Str::of('This is my name')->before('my name');

// 'This is '

beforeLast {#collection-method}

beforeLast 方法返回字符串中指定值最后一次出现前的所有内容:

use Illuminate\Support\Str;

$slice = Str::of('This is my name')->beforeLast('is');

// 'This '

camel {#collection-method}

camel 方法将指定字符串转换为 驼峰式 表示方法:

use Illuminate\Support\Str;

$converted = Str::of('foo_bar')->camel();

// fooBar

contains {#collection-method}

contains 方法判断指定字符串中是否包含另一指定字符串(区分大小写):

use Illuminate\Support\Str;

$contains = Str::of('This is my name')->contains('my');

// true

您亦可以传递数组的值的形式来判断指定字符串是否包含数组中的任一值:

use Illuminate\Support\Str;

$contains = Str::of('This is my name')->contains(['my', 'foo']);

// true

containsAll {#collection-method}

containsAll 方法用于判断指定字符串是否包含指定数组中的所有值:

use Illuminate\Support\Str;

$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);

// true

dirname {#collection-method}

dirname 方法用于返回指定字符串的父级目录部分:

use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz')->dirname();

// '/foo/bar'

您亦可指定您想要从字符串中删除多少个目录级别,该参数是可选的:

use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz')->dirname(2);

// '/foo'

endsWith {#collection-method}

endsWith 方法用于判断指定字符串是否以另一指定字符串结尾:

use Illuminate\Support\Str;

$result = Str::of('This is my name')->endsWith('name');

// true

您亦可以传递数组的值的形式来判断指定字符串是否包含指定数组中的任一值:

use Illuminate\Support\Str;

$result = Str::of('This is my name')->endsWith(['name', 'foo']);

// true

$result = Str::of('This is my name')->endsWith(['this', 'foo']);

// false

exactly {#collection-method}

exactly 方法用于判断指定字符串是否与另一字符串完全匹配:

use Illuminate\Support\Str;

$result = Str::of('Laravel')->exactly('Laravel');

// true

explode {#collection-method}

explode 方法使用指定的分割符分割字符串,并返回包含字符串每个部分的集合:

use Illuminate\Support\Str;

$collection = Str::of('foo bar baz')->explode(' ');

// collect(['foo', 'bar', 'baz'])

finish {#collection-method}

finish 方法用于判断指定字符串末尾是否有特定字符,若没有,则将其添加到字符串末尾:

use Illuminate\Support\Str;

$adjusted = Str::of('this/string')->finish('/');

// this/string/

$adjusted = Str::of('this/string/')->finish('/');

// this/string/

is {#collection-method}

is 方法用于判断字符串是否与指定模式匹配。星号 * 用于表示通配符:

use Illuminate\Support\Str;

$matches = Str::of('foobar')->is('foo*');

// true

$matches = Str::of('foobar')->is('baz*');

// false

isAscii {#collection-method}

isAscii 方法用于判断指定字符串是否是 ASCII 字符串:

use Illuminate\Support\Str;

$result = Str::of('Taylor')->isAscii();

// true

$result = Str::of('ü')->isAscii();

// false

isEmpty {#collection-method}

isEmpty 方法用于判断指定字符串是否为空:

use Illuminate\Support\Str;

$result = Str::of('  ')->trim()->isEmpty();

// true

$result = Str::of('Laravel')->trim()->isEmpty();

// false

isNotEmpty {#collection-method}

isNotEmpty 方法用于判断指定字符串是否不为空:

use Illuminate\Support\Str;

$result = Str::of('  ')->trim()->isNotEmpty();

// false

$result = Str::of('Laravel')->trim()->isNotEmpty();

// true

kebab {#collection-method}

kebab 方法将指定字符串转换为 烤串式( kebab-case ) 表示形式:

use Illuminate\Support\Str;

$converted = Str::of('fooBar')->kebab();

// foo-bar

length {#collection-method}

length 方法返回指定字符串的长度:

use Illuminate\Support\Str;

$length = Str::of('Laravel')->length();

// 7

limit {#collection-method}

limit 方法用于将指定字符串切割为指定长度:

use Illuminate\Support\Str;

$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);

// The quick brown fox...

您亦可通过第二个参数来改变追加到末尾的字符串:

use Illuminate\Support\Str;

$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');

// The quick brown fox (...)

lower {#collection-method}

lower 方法将指定字符串转换为小写:

use Illuminate\Support\Str;

$result = Str::of('LARAVEL')->lower();

// 'laravel'

ltrim {#collection-method}

ltrim 方法移除字符串左端指定的字符:

use Illuminate\Support\Str;

$string = Str::of('  Laravel  ')->ltrim();

// 'Laravel  '

$string = Str::of('/Laravel/')->ltrim('/');

// 'Laravel/'

markdown {#collection-method}

markdown 方法将 Github 风格的 Markdown 转换为 HTML:

use Illuminate\Support\Str;

$html = Str::of('# Laravel')->markdown();

// <h1>Laravel</h1>

$html = Str::of('# Taylor <b>Otwell</b>')->markdown([
    'html_input' => 'strip',
]);

// <h1>Taylor Otwell</h1>

match {#collection-method}

match 方法将会返回字符串和指定正则表达式匹配的部分:

use Illuminate\Support\Str;

$result = Str::of('foo bar')->match('/bar/');

// 'bar'

$result = Str::of('foo bar')->match('/foo (.*)/');

// 'bar'

matchAll {#collection-method}

matchAll 方法将会返回一个集合,该集合包含了指定字符串中与指定正则表达式匹配的部分:

use Illuminate\Support\Str;

$result = Str::of('bar foo bar')->matchAll('/bar/');

// collect(['bar', 'bar'])

如果您在正则表达式中指定了一个匹配组, Laravel 将会返回与该组匹配的集合:

use Illuminate\Support\Str;

$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');

// collect(['un', 'ly']);

如果没有找到任何匹配项,则返回空集合。

padBoth {#collection-method}

padBoth 方法包装了 PHP 的 str_pad 函数,在指定字符串的两侧填充上另一字符串,直至该字符串到达指定的长度:

use Illuminate\Support\Str;

$padded = Str::of('James')->padBoth(10, '_');

// '__James___'

$padded = Str::of('James')->padBoth(10);

// '  James   '

padLeft {#collection-method}

The padLeft 方法包装了 PHP 的 str_pad 函数,在指定字符串的左侧填充上另一字符串,直至该字符串到达指定的长度:

use Illuminate\Support\Str;

$padded = Str::of('James')->padLeft(10, '-=');

// '-=-=-James'

$padded = Str::of('James')->padLeft(10);

// '     James'

padRight {#collection-method}

padRight 方法包装了 PHP 的 str_pad 函数,在指定字符串的右侧填充上另一字符串,直至该字符串到达指定的长度:

use Illuminate\Support\Str;

$padded = Str::of('James')->padRight(10, '-');

// 'James-----'

$padded = Str::of('James')->padRight(10);

// 'James     '

pipe {#collection-method}

pipe 方法通过将字符串的当前值传递给给定的匿名函数来转换字符串:

use Illuminate\Support\Str;

$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');

// 'Checksum: a5c95b86291ea299fcbe64458ed12702'

$closure = Str::of('foo')->pipe(function ($str) {
    return 'bar';
});

// 'bar'

plural {#collection-method}

plural 方法将单数形式的字符串转换为复数形式。目前该函数仅支持英语:

use Illuminate\Support\Str;

$plural = Str::of('car')->plural();

// cars

$plural = Str::of('child')->plural();

// children

您亦可给该函数提供一个整数作为第二个参数用于检索单数或复数形式:

use Illuminate\Support\Str;

$plural = Str::of('child')->plural(2);

// children

$plural = Str::of('child')->plural(1);

// child

prepend {#collection-method}

prepend 方法用于在指定字符串的开头插入另一指定字符串:

use Illuminate\Support\Str;

$string = Str::of('Framework')->prepend('Laravel ');

// Laravel Framework

replace {#collection-method}

replace 方法用于将字符串中的指定字符串替换为另一指定字符串:

use Illuminate\Support\Str;

$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');

// Laravel 7.x

replaceArray {#集合-方法}

replaceArray方法使用数组顺序替换字符串中的给定值:

    use Illuminate\Support\Str;

    $string = '这个事件是在什么到什么时间段触发';

    $replaced = Str::of($string)->replaceArray('?', ['8:30', '9:00']);

    // 事件将在8:30到9:00之间触发

replaceFirst {#集合-方法}

replaceFirst方法替换字符串中给定值的第一个匹配项:

use Illuminate\Support\Str;

$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a');

// a quick brown fox jumps over the lazy dog

replaceLast {#集合-方法}

replaceLast方法替换字符串中给定值的最后一次出现:

    use Illuminate\Support\Str;

    $replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a');

    // the quick brown fox jumps over a lazy dog

replaceMatches {#集合-方法}

replaceMatches方法用给定的替换字符串替换与模式匹配的字符串的所有部分:

    use Illuminate\Support\Str;

    $replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '')

    // '15015551000'

replaceMatches方法还接受一个闭包,该闭包将被与给定模式匹配的字符串的每个部分调用,从而允许您在闭包中执行替换逻辑并返回替换的值:

    use Illuminate\Support\Str;

    $replaced = Str::of('123')->replaceMatches('/\d/', function ($match) {
        return '['.$match[0].']';
    });

    // '[1][2][3]'

rtrim {#collection-method}

rtrim方法修剪给定字符串的右侧:

    use Illuminate\Support\Str;

    $string = Str::of('  Laravel  ')->rtrim();

    // '  Laravel'

    $string = Str::of('/Laravel/')->rtrim('/');

    // '/Laravel'

singular {#collection-method}

singular方法将字符串转换为其单数形式。此函数当前仅支持英语:

use Illuminate\Support\Str;

$singular = Str::of('cars')->singular();

// car

$singular = Str::of('children')->singular();

// child

slug {#collection-method}

slug方法从给定字符串生成URL友好的slug

    use Illuminate\Support\Str;

    $slug = Str::of('Laravel Framework')->slug('-');

    // laravel-framework

snake {#collection-method}

snake方法将给定字符串转换为snake_case

    use Illuminate\Support\Str;

    $converted = Str::of('fooBar')->snake();

    // foo_bar

split {#collection-method}

split方法使用正则表达式将字符串拆分为集合:

use Illuminate\Support\Str;

$segments = Str::of('one, two, three')->split('/[\s,]+/');

// collect(["one", "two", "three"])

start {#collection-method}

start方法将给定值的单个实例添加到字符串中,前提是该字符串尚未以该值开头:

    use Illuminate\Support\Str;

    $adjusted = Str::of('this/string')->start('/');

    // /this/string

    $adjusted = Str::of('/this/string')->start('/');

    // /this/string

startsWith {#collection-method}

startsWith方法确定给定字符串是否以给定值开头:

    use Illuminate\Support\Str;

    $result = Str::of('This is my name')->startsWith('This');

    // true

studly {#collection-method}

studly方法将给定字符串转换为StudlyCase

    use Illuminate\Support\Str;

    $converted = Str::of('foo_bar')->studly();

    // FooBar

substr {#collection-method}

substr方法返回由给定的起始参数和长度参数指定的字符串部分:

    use Illuminate\Support\Str;

    $string = Str::of('Laravel Framework')->substr(8);

    // Framework

    $string = Str::of('Laravel Framework')->substr(8, 5);

    // Frame

tap {#collection-method}

tap方法将字符串传递给给定的闭包,允许您在不影响字符串本身的情况下检查字符串并与之交互。tap方法返回原始字符串,而不管闭包返回什么:

    use Illuminate\Support\Str;

    $string = Str::of('Laravel')
        ->append(' Framework')
        ->tap(function ($string) {
            dump('String after append: ' . $string);
        })
        ->upper();

    // LARAVEL FRAMEWORK

title {#collection-method}

title方法将给定字符串转换为title Case

    use Illuminate\Support\Str;

    $converted = Str::of('a nice title uses the correct case')->title();

    // A Nice Title Uses The Correct Case

trim {#collection-method}

trim方法修剪给定字符串:

    use Illuminate\Support\Str;

    $string = Str::of('  Laravel  ')->trim();

    // 'Laravel'

    $string = Str::of('/Laravel/')->trim('/');

    // 'Laravel'

ucfirst {#collection-method}

ucfirst方法返回第一个字符大写的给定字符串:

    use Illuminate\Support\Str;

    $string = Str::of('foo bar')->ucfirst();

    // Foo bar

upper {#collection-method}

upper方法将给定字符串转换为大写:

    use Illuminate\Support\Str;

    $adjusted = Str::of('laravel')->upper();

    // LARAVEL

when {#collection-method}

如果给定的条件为true,则when方法调用给定的闭包。闭包将接收一个流畅字符串实例:

    use Illuminate\Support\Str;

    $string = Str::of('Taylor')
                    ->when(true, function ($string) {
                        return $string->append(' Otwell');
                    });

    // 'Taylor Otwell'

如果需要,可以将另一个闭包作为第三个参数传递给when方法。如果条件参数的计算结果为false,则将执行此闭包。

whenEmpty {#collection-method}

如果字符串为空,whenEmpty方法将调用给定的闭包。如果闭包返回一个值,whenEmpty方法也将返回该值。如果闭包不返回值,则将返回流畅字符串实例:

    use Illuminate\Support\Str;

    $string = Str::of('  ')->whenEmpty(function ($string) {
        return $string->trim()->prepend('Laravel');
    });

    // 'Laravel'

words {#collection-method}

words方法限制字符串中的字数。如有必要,可以指定附加到截断字符串的附加字符串:

    use Illuminate\Support\Str;

    $string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');

    // Perfectly balanced, as >>>

URLs

action() {#collection-method}

action函数为给定的控制器操作生成URL:

    use App\Http\Controllers\HomeController;

    $url = action([HomeController::class, 'index']);

如果该方法接受路由参数,则可以将它们作为第二个参数传递给该方法:

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

asset() {#collection-method}

asset函数使用请求的当前方案(HTTP或HTTPS)为资产生成URL:

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

您可以通过在.env文件中设置ASSET_URL变量来配置资产URL主机。如果您将资产托管在外部服务(如Amazon S3或其他CDN)上,这将非常有用:

    // ASSET_URL=http://example.com/assets

    $url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpg

route() {#collection-method}

route函数为给定的 命名路由:

    $url = route('route.name');

如果路由接受参数,则可以将其作为第二个参数传递给函数:

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

默认情况下,route函数生成一个绝对URL。如果要生成相对URL,可以将false作为第三个参数传递给函数:

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

secure_asset() {#collection-method}

secure_asset函数使用HTTPS为资产生成URL:

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

secure_url() {#collection-method}

secure_url函数的作用是生成一个指向给定路径的完全限定的HTTPS url。可以在函数的第二个参数中传递其他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 方法抛出一个 HTTP 异常交给异常处理:

abort(403);

您还可以提供应发送到浏览器的异常消息和自定义 HTTP 响应标头:

abort(403, 'Unauthorized.', $headers);

abort_if() {#collection-method}

如果给定的布尔表达式评估为trueabort_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 方法放回服务容器实例:

$container = app();

你可以传递类或接口名称来从容器中解析它:

$api = app('HelpSpot\API');

auth() {#collection-method}

auth 函数返回一个 认证器 实例. 您可以使用它来替代 Auth 门面:

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

如果需要,你可以指定你想要访问的认证实例:

$user = auth('admin')->user();

back() {#collection-method}

back 函数生成一个 重定向 HTTP 响应 到用户之前的位置

return back($status = 302, $headers = [], $fallback = '/');

return back();

bcrypt() {#collection-method}

The bcrypt 函数 哈希 使用 Bcrypt 对给定的值进行散列。 你可以使用它替代 Hash 门面:

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

blank() {#collection-method}

blank 函数判断给定的值是否为空:

blank('');
blank('   ');
blank(null);
blank(collect());

// true

blank(0);
blank(true);
blank(false);

// false

如果想使用与 blank, 函数相反的方法,请看 filled 函数.

broadcast() {#collection-method}

broadcast 函数将 广播 给定的 事件 到它的监听器:

broadcast(new UserRegistered($user));

broadcast(new UserRegistered($user))->toOthers();

cache() {#collection-method}

cache 函数可以从 缓存 中获取值, 如果缓存中给定的键不存在,将返回一个可选的默认值:

$value = cache('key');

$value = cache('key', 'default');

你可以通过向函数添加键值对数组来设置缓存项。与此同时,你还应该传递有效的分钟数或者缓存的持续时间来设置缓存过期时间 :

cache(['key' => 'value'], 300);

cache(['key' => 'value'], now()->addSeconds(10));

class_uses_recursive() {#collection-method}

class_uses_recursive 函数返回一个类使用的所有 traits, 包括它所有父类使用的 traits :

$traits = class_uses_recursive(App\Models\User::class);

collect() {#collection-method}

collect 函数根据给定的值创建一个 collection 实例:

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

config() {#collection-method}

config 函数获取 configuration 变量的值。 可以使用「点」语法访问配置的值,其中包括文件的名称和访问的选项,如果访问的配置选项不存在,你可以指定一个默认值并且返回这个默认值:

$value = config('app.timezone');

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

你也可以在运行时通过传递一个键/值对数组来设置配置变量, 但是,请注意,此函数仅影响当前请求的配置值,不会更新实际的配置值:

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

cookie() {#collection-method}

cookie 函数创建一个新的 cookie 实例 :

$cookie = cookie('name', 'value', $minutes);

csrf_field() {#collection-method}

csrf_field 函数生成一个包含 CSRF 令牌值的 HTML 输入表单字段 hidden 。例如,使用 Blade语法:

{{ csrf_field() }}

csrf_token() {#collection-method}

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

$token = csrf_token();

dd() {#collection-method}

dd 函数打印输出给定的变量并且结束脚本运行:

dd($value);

dd($value1, $value2, $value3, ...);

如果你不停止执行脚本,那么可以使用 dump 函数。

dispatch() {#collection-method}

dispatch 函数将给定的 任务 推送到 Laravel 任务队列:

dispatch(new App\Jobs\SendEmails);

dispatch_now() {#collection-method}

dispatch_now 函数立即运行给定的 任务 并从 handle 方法返回值:

$result = dispatch_now(new App\Jobs\SendEmails);

dump() {#collection-method}

dump 打印给定的变量:

dump($value);

dump($value1, $value2, $value3, ...);

如果你想要在打印后停止执行脚本,可以使用 dd 函数。

env() {#collection-method}

env 函数可以获取 环境变量 配置的值或者返回默认值:

$env = env('APP_ENV');

$env = env('APP_ENV', 'production');

注意:如果你在部署过程中执行了 config:cache 命令 , 那么你应该确保只从配置文件中调用 env 函数. 一旦配置被缓存, .env 文件将不再次加载,所有对 env 函数的调用将返回 null

event() {#collection-method}

event函数向监听器派发给定 事件 :

event(new UserRegistered($user));

filled() {#collection-method}

filled 函数返回是否不为「空」:

filled(0);
filled(true);
filled(false);

// true

filled('');
filled('   ');
filled(null);
filled(collect());

// false

对于作用与 filled, 相反的方法,可以查看 blank 方法。

info() {#collection-method}

info 函数将信息写入 log:

info('Some helpful information!');

可以将上下文数据数组传递给此函数:

info('User login attempt failed.', ['id' => $user->id]);

logger() {#collection-method}

logger 函数可以被用于将 debug 级别的消息写入 log:

logger('Debug message');

上下文数据数组也可以传递给函数:

logger('User has logged in.', ['id' => $user->id]);

如果不带参数调用此函数,它将返回 logger 实例:

logger()->error('You are not allowed here.');

method_field() {#collection-method}

method_field 函数生成包含模仿表单 HTTP 动作的 HTML hidden 域。下面的例子使用了 Blade语法:

<form method="POST">
    {{ method_field('DELETE') }}
</form>

now() {#collection-method}

now 函数为当前时间创建一个新的 Illuminate\Support\Carbon 实例:

$now = now();

old() {#collection-method}

old 函数 获取 写入 session旧的输入值 :

$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 $user->name;
});

policy() {#collection-method}

policy 方法为给定的类获取 policy 实例

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

redirect() {#collection-method}

redirect 函数返回 重定向 HTTP 响应,如果不带参数调用则返回重定向器实例:

return redirect($to = null, $status = 302, $headers = [], $https = null);

return redirect('/home');

return redirect()->route('route.name');

report() {#collection-method}

report 函数使用 异常处理器report 方法报告异常:

report($e);

report 函数也接受一个字符串作为参数。当给函数一个字符串时,函数将创建一个异常,并将该字符串作为其消息:

report('Something went wrong.');

request() {#collection-method}

request 函数返回当前的 request实例或从当前请求中获取输入字段的值:

$request = request();

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

rescue() {#collection-method}

rescue 函数执行给定的闭包,并且捕获其执行过程中引发的任何异常。捕获的所有异常都将传递给 异常处理器;然后继续处理此次请求:

return rescue(function () {
    return $this->method();
});

还可以为其传递第二个参数。这个参数将作为执行闭包引发异常时的「默认」值:

return rescue(function () {
    return $this->method();
}, false);

return rescue(function () {
    return $this->method();
}, function () {
    return $this->failure();
});

resolve() {#collection-method}

resolve 使用 服务容器 解析给定名称的类或接口的实例:

$api = resolve('HelpSpot\API');

response() {#collection-method}

response 函数创建 响应 实例,或者获取响应工厂的实例:

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

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

retry() {#collection-method}

retry 函数尝试执行给定的回调,直到达到给定的最大尝试阈值。如果回调没有抛出异常,回调返回值将被返回。如果回调抛出异常,将自动重试。达到最大尝试次数,将抛出异常:

return retry(5, function () {
    // 尝试5次,在两次尝试之间休息100毫秒…
}, 100);

session() {#collection-method}

session 函数用于获取或设置 session 值:

$value = session('key');

可以向该函数传递键值对数组来设置 session 值:

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

不带参数调用此函数,则返回 session 实例:

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

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

tap() {#collection-method}

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,
]);

要向类中添加 tap 方法,可以将 Illuminate\Support\Traits\Tappable 特征添加到类中。 此特征的 tap 方法接受闭包作为其唯一参数。 对象实例本身将传递给闭包,然后由 tap 方法返回:

return $user->tap(function ($user) {
    //
});

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

today() {#collection-method}

today 函数根据当前日期创建新的 Illuminate\Support\Carbon 实例:

$today = today();

trait_uses_recursive() {#collection-method}

trait_uses_recursive 返回被 trait 使用的全部 trait

$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);

transform() {#collection-method}

transform 函数执行基于(非)给定值的 闭包,并返回闭包的结果
$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 函数根据指定的参数创建一个新的 验证器 实例。方便起见可以用它来代替 Validator facade:

$validator = validator($data, $rules, $messages);

value() {#collection-method}

value 函数返回给定值。如果传递闭包给此函数,将执行闭包并返回闭包调用的结果:

$result = value(true);

// true

$result = value(function () {
    return false;
});

// false

view() {#collection-method}

view 函数获取一个 view 实例:

return view('auth.login');

with() {#collection-method}

with 函数返回给定的值。如果传递了一个 闭包 给第二个参数,那么会返回 闭包 执行的结果:

$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

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/laravel/8.5/hel...

译文地址:https://learnku.com/docs/laravel/8.5/hel...

上一篇 下一篇
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
贡献者:21
讨论数量: 3
发起讨论 只看当前版本


PerFe
Arr::dot() 对二维数组返回预期不一致
0 个点赞 | 2 个回复 | 代码速记 | 课程版本 8.x
wolfgreen
transform() 和 with() 不是差不多么?
0 个点赞 | 0 个回复 | 分享 | 课程版本 5.5
xingchen
直接使用 (string) Str::orderedUuid ();会报错!
0 个点赞 | 0 个回复 | 分享 | 课程版本 5.6