Skip to content

辅助函数

介绍

Laravel 包含多种全局 "辅助" PHP 函数。许多这些函数被框架本身使用;然而,如果您觉得方便,也可以在自己的应用程序中使用它们。

可用方法

数组和对象

路径

字符串

流畅字符串

URL

杂项

方法列表

数组和对象

Arr::accessible()

Arr::accessible 方法确定给定的值是否可以作为数组访问:

php
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()

Arr::add 方法在给定键不存在或设置为 null 时,将给定的键/值对添加到数组中:

php
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()

Arr::collapse 方法将数组的数组折叠成一个单一数组:

php
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()

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

php
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()

Arr::divide 方法返回两个数组:一个包含给定数组的键,另一个包含值:

php
use Illuminate\Support\Arr;

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

// $keys: ['name']

// $values: ['Desk']

Arr::dot()

Arr::dot 方法将多维数组展平为单级数组,使用 "点" 符号表示深度:

php
use Illuminate\Support\Arr;

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

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

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

Arr::except()

Arr::except 方法从数组中移除给定的键/值对:

php
use Illuminate\Support\Arr;

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

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

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

Arr::exists()

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

php
use Illuminate\Support\Arr;

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

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

// true

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

// false

Arr::first()

Arr::first 方法返回通过给定真值测试的数组的第一个元素:

php
use Illuminate\Support\Arr;

$array = [100, 200, 300];

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

// 200

该方法的第三个参数也可以传递一个默认值。如果没有值通过真值测试,将返回此值:

php
use Illuminate\Support\Arr;

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

Arr::flatten()

Arr::flatten 方法将多维数组展平为单级数组:

php
use Illuminate\Support\Arr;

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

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

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

Arr::forget()

Arr::forget 方法使用 "点" 符号从深度嵌套的数组中移除给定的键/值对:

php
use Illuminate\Support\Arr;

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

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

// ['products' => []]

Arr::get()

Arr::get 方法使用 "点" 符号从深度嵌套的数组中检索值:

php
use Illuminate\Support\Arr;

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

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

// 100

Arr::get 方法还接受一个默认值,如果指定的键不存在于数组中,将返回此值:

php
use Illuminate\Support\Arr;

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

// 0

Arr::has()

Arr::has 方法使用 "点" 符号检查给定项或项是否存在于数组中:

php
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()

Arr::hasAny 方法使用 "点" 符号检查给定集合中的任何项是否存在于数组中:

php
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()

Arr::isAssoc 方法返回 true 如果给定数组是关联数组。一个数组被认为是 "关联" 的,如果它没有从零开始的顺序数字键:

php
use Illuminate\Support\Arr;

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

// true

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

// false

Arr::isList()

Arr::isList 方法返回 true 如果给定数组的键是从零开始的顺序整数:

php
use Illuminate\Support\Arr;

$isList = Arr::isList(['foo', 'bar', 'baz']);

// true

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

// false

Arr::join()

Arr::join 方法使用字符串连接数组元素。使用此方法的第二个参数,您还可以指定数组最后一个元素的连接字符串:

php
use Illuminate\Support\Arr;

$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];

$joined = Arr::join($array, ', ');

// Tailwind, Alpine, Laravel, Livewire

$joined = Arr::join($array, ', ', ' and ');

// Tailwind, Alpine, Laravel and Livewire

Arr::keyBy()

Arr::keyBy 方法通过给定键对数组进行键控。如果多个项具有相同的键,则只有最后一个会出现在新数组中:

php
use Illuminate\Support\Arr;

$array = [
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
];

$keyed = Arr::keyBy($array, 'product_id');

/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

Arr::last()

Arr::last 方法返回通过给定真值测试的数组的最后一个元素:

php
use Illuminate\Support\Arr;

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

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

// 300

该方法的第三个参数也可以传递一个默认值。如果没有值通过真值测试,将返回此值:

php
use Illuminate\Support\Arr;

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

Arr::map()

Arr::map 方法遍历数组并将每个值和键传递给给定的回调。数组值将被回调返回的值替换:

php
use Illuminate\Support\Arr;

$array = ['first' => 'james', 'last' => 'kirk'];

$mapped = Arr::map($array, function ($value, $key) {
    return ucfirst($value);
});

// ['first' => 'James', 'last' => 'Kirk']

Arr::only()

Arr::only 方法仅返回给定数组中指定的键/值对:

php
use Illuminate\Support\Arr;

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

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

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

Arr::pluck()

Arr::pluck 方法检索给定键的所有值:

php
use Illuminate\Support\Arr;

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

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

// ['Taylor', 'Abigail']

您还可以指定希望结果列表如何键控:

php
use Illuminate\Support\Arr;

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

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

Arr::prepend()

Arr::prepend 方法将一个项推到数组的开头:

php
use Illuminate\Support\Arr;

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

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

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

如果需要,您可以指定应为值使用的键:

php
use Illuminate\Support\Arr;

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

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

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

Arr::prependKeysWith()

Arr::prependKeysWith 方法为关联数组的所有键名添加给定前缀:

php
use Illuminate\Support\Arr;

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

$keyed = Arr::prependKeysWith($array, 'product.');

/*
    [
        'product.name' => 'Desk',
        'product.price' => 100,
    ]
*/

Arr::pull()

Arr::pull 方法返回并移除数组中的键/值对:

php
use Illuminate\Support\Arr;

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

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

// $name: Desk

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

该方法的第三个参数也可以传递一个默认值。如果键不存在,将返回此值:

php
use Illuminate\Support\Arr;

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

Arr::query()

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

php
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()

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

php
use Illuminate\Support\Arr;

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

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

// 4 - (随机检索)

您还可以指定要返回的项数作为可选的第二个参数。请注意,提供此参数将返回一个数组,即使只需要一个项:

php
use Illuminate\Support\Arr;

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

// [2, 5] - (随机检索)

Arr::set()

Arr::set 方法使用 "点" 符号在深度嵌套的数组中设置值:

php
use Illuminate\Support\Arr;

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

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

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

Arr::shuffle()

Arr::shuffle 方法随机打乱数组中的项:

php
use Illuminate\Support\Arr;

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

// [3, 2, 5, 1, 4] - (随机生成)

Arr::sort()

Arr::sort 方法按值对数组进行排序:

php
use Illuminate\Support\Arr;

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

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

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

您还可以通过给定闭包的结果对数组进行排序:

php
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::sortDesc()

Arr::sortDesc 方法按值对数组进行降序排序:

php
use Illuminate\Support\Arr;

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

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

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

您还可以通过给定闭包的结果对数组进行排序:

php
use Illuminate\Support\Arr;

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

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

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

Arr::sortRecursive()

Arr::sortRecursive 方法递归地对数组进行排序,使用 sort 函数对数字索引的子数组进行排序,使用 ksort 函数对关联子数组进行排序:

php
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::toCssClasses()

Arr::toCssClasses 条件编译 CSS 类字符串。该方法接受一个类数组,其中数组键包含您希望添加的类或类,而值是一个布尔表达式。如果数组元素有一个数字键,它将始终包含在渲染的类列表中:

php
use Illuminate\Support\Arr;

$isActive = false;
$hasError = true;

$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError];

$classes = Arr::toCssClasses($array);

/*
    'p-4 bg-red'
*/

此方法支持 Laravel 的功能,允许 与 Blade 组件的属性包合并类 以及 @class Blade 指令

Arr::undot()

Arr::undot 方法将使用 "点" 符号的单维数组扩展为多维数组:

php
use Illuminate\Support\Arr;

$array = [
    'user.name' => 'Kevin Malone',
    'user.occupation' => 'Accountant',
];

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

// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]

Arr::where()

Arr::where 方法使用给定的闭包过滤数组:

php
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::whereNotNull()

Arr::whereNotNull 方法从给定数组中移除所有 null 值:

php
use Illuminate\Support\Arr;

$array = [0, null];

$filtered = Arr::whereNotNull($array);

// [0 => 0]

Arr::wrap()

Arr::wrap 方法将给定值包装在数组中。如果给定值已经是数组,则将返回不做修改的数组:

php
use Illuminate\Support\Arr;

$string = 'Laravel';

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

// ['Laravel']

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

php
use Illuminate\Support\Arr;

$array = Arr::wrap(null);

// []

data_fill()

data_fill 函数使用 "点" 符号在嵌套数组或对象中设置缺失值:

php
$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]]]

此函数还接受星号作为通配符,并将相应地填充目标:

php
$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 函数使用 "点" 符号从嵌套数组或对象中检索值:

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

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

// 100

data_get 函数还接受一个默认值,如果指定的键未找到,将返回此值:

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

// 0

该函数还接受使用星号的通配符,可以定位数组或对象的任何键:

php
$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()

data_set 函数使用 "点" 符号在嵌套数组或对象中设置值:

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

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

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

此函数还接受使用星号的通配符,并将相应地在目标上设置值:

php
$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 作为函数的第四个参数传递:

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

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

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

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

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

$first = head($array);

// 100

last()

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

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

$last = last($array);

// 300

路径

app_path()

app_path 函数返回应用程序的 app 目录的完全限定路径。您还可以使用 app_path 函数生成相对于应用程序目录的文件的完全限定路径:

php
$path = app_path();

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

base_path()

base_path 函数返回应用程序根目录的完全限定路径。您还可以使用 base_path 函数生成相对于项目根目录的给定文件的完全限定路径:

php
$path = base_path();

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

config_path()

config_path 函数返回应用程序的 config 目录的完全限定路径。您还可以使用 config_path 函数生成应用程序配置目录中给定文件的完全限定路径:

php
$path = config_path();

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

database_path()

database_path 函数返回应用程序的 database 目录的完全限定路径。您还可以使用 database_path 函数生成数据库目录中给定文件的完全限定路径:

php
$path = database_path();

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

lang_path()

lang_path 函数返回应用程序的 lang 目录的完全限定路径。您还可以使用 lang_path 函数生成目录中给定文件的完全限定路径:

php
$path = lang_path();

$path = lang_path('en/messages.php');

mix()

mix 函数返回 版本化 Mix 文件 的路径:

php
$path = mix('css/app.css');

public_path()

public_path 函数返回应用程序的 public 目录的完全限定路径。您还可以使用 public_path 函数生成公共目录中给定文件的完全限定路径:

php
$path = public_path();

$path = public_path('css/app.css');

resource_path()

resource_path 函数返回应用程序的 resources 目录的完全限定路径。您还可以使用 resource_path 函数生成资源目录中给定文件的完全限定路径:

php
$path = resource_path();

$path = resource_path('sass/app.scss');

storage_path()

storage_path 函数返回应用程序的 storage 目录的完全限定路径。您还可以使用 storage_path 函数生成存储目录中给定文件的完全限定路径:

php
$path = storage_path();

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

字符串

__()

__ 函数使用您的 本地化文件 翻译给定的翻译字符串或翻译键:

php
echo __('Welcome to our application');

echo __('messages.welcome');

如果指定的翻译字符串或键不存在,__ 函数将返回给定值。因此,使用上面的示例,如果该翻译键不存在,__ 函数将返回 messages.welcome

class_basename()

class_basename 函数返回给定类的类名,并去除类的命名空间:

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

// Baz

e()

e 函数运行 PHP 的 htmlspecialchars 函数,默认情况下设置 double_encode 选项为 true

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

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

preg_replace_array()

preg_replace_array 函数使用数组顺序替换字符串中的给定模式:

php
$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()

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

php
use Illuminate\Support\Str;

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

// ' my name'

Str::afterLast()

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

php
use Illuminate\Support\Str;

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

// 'Controller'

Str::ascii()

Str::ascii 方法将尝试将字符串音译为 ASCII 值:

php
use Illuminate\Support\Str;

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

// 'u'

Str::before()

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

php
use Illuminate\Support\Str;

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

// 'This is '

Str::beforeLast()

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

php
use Illuminate\Support\Str;

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

// 'This '

Str::between()

Str::between 方法返回字符串中两个值之间的部分:

php
use Illuminate\Support\Str;

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

// ' is my '

Str::betweenFirst()

Str::betweenFirst 方法返回字符串中两个值之间的最小可能部分:

php
use Illuminate\Support\Str;

$slice = Str::betweenFirst('[a] bc [d]', '[', ']');

// 'a'

Str::camel()

Str::camel 方法将给定字符串转换为 camelCase

php
use Illuminate\Support\Str;

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

// fooBar

Str::contains()

Str::contains 方法确定给定字符串是否包含给定值。此方法区分大小写:

php
use Illuminate\Support\Str;

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

// true

您还可以传递一个值数组,以确定给定字符串是否包含数组中的任何值:

php
use Illuminate\Support\Str;

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

// true

Str::containsAll()

Str::containsAll 方法确定给定字符串是否包含给定数组中的所有值:

php
use Illuminate\Support\Str;

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

// true

Str::endsWith()

Str::endsWith 方法确定给定字符串是否以给定值结尾:

php
use Illuminate\Support\Str;

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

// true

您还可以传递一个值数组,以确定给定字符串是否以数组中的任何值结尾:

php
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::excerpt()

Str::excerpt 方法从给定字符串中提取与该字符串中某个短语的第一个实例匹配的摘录:

php
use Illuminate\Support\Str;

$excerpt = Str::excerpt('This is my name', 'my', [
    'radius' => 3
]);

// '...is my na...'

radius 选项,默认为 100,允许您定义应出现在截断字符串两侧的字符数。

此外,您可以使用 omission 选项定义将被添加到截断字符串的字符串:

php
use Illuminate\Support\Str;

$excerpt = Str::excerpt('This is my name', 'name', [
    'radius' => 3,
    'omission' => '(...) '
]);

// '(...) my name'

Str::finish()

Str::finish 方法在字符串末尾添加给定值的单个实例,如果字符串尚未以该值结尾:

php
use Illuminate\Support\Str;

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

// this/string/

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

// this/string/

Str::headline()

Str::headline 方法将由大小写、连字符或下划线分隔的字符串转换为以空格分隔的字符串,并将每个单词的首字母大写:

php
use Illuminate\Support\Str;

$headline = Str::headline('steve_jobs');

// Steve Jobs

$headline = Str::headline('EmailNotificationSent');

// Email Notification Sent

Str::inlineMarkdown()

Str::inlineMarkdown 方法使用 CommonMark 将 GitHub 风格的 Markdown 转换为内联 HTML。然而,与 markdown 方法不同,它不会将所有生成的 HTML 包裹在块级元素中:

php
use Illuminate\Support\Str;

$html = Str::inlineMarkdown('**Laravel**');

// <strong>Laravel</strong>

Str::is()

Str::is 方法确定给定字符串是否与给定模式匹配。星号可以用作通配符:

php
use Illuminate\Support\Str;

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

// true

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

// false

Str::isAscii()

Str::isAscii 方法确定给定字符串是否为 7 位 ASCII:

php
use Illuminate\Support\Str;

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

// true

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

// false

Str::isJson()

Str::isJson 方法确定给定字符串是否为有效的 JSON:

php
use Illuminate\Support\Str;

$result = Str::isJson('[1,2,3]');

// true

$result = Str::isJson('{"first": "John", "last": "Doe"}');

// true

$result = Str::isJson('{first: "John", last: "Doe"}');

// false

Str::isUlid()

Str::isUlid 方法确定给定字符串是否为有效的 ULID:

php
use Illuminate\Support\Str;

$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');

// true

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

// false

Str::isUuid()

Str::isUuid 方法确定给定字符串是否为有效的 UUID:

php
use Illuminate\Support\Str;

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

// true

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

// false

Str::kebab()

Str::kebab 方法将给定字符串转换为 kebab-case

php
use Illuminate\Support\Str;

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

// foo-bar

Str::lcfirst()

Str::lcfirst 方法返回首字母小写的给定字符串:

php
use Illuminate\Support\Str;

$string = Str::lcfirst('Foo Bar');

// foo Bar

Str::length()

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

php
use Illuminate\Support\Str;

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

// 7

Str::limit()

Str::limit 方法将给定字符串截断为指定长度:

php
use Illuminate\Support\Str;

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

// The quick brown fox...

您可以传递第三个参数来更改将在截断字符串末尾附加的字符串:

php
use Illuminate\Support\Str;

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

// The quick brown fox (...)

Str::lower()

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

php
use Illuminate\Support\Str;

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

// laravel

Str::markdown()

Str::markdown 方法使用 CommonMark 将 GitHub 风格的 Markdown 转换为 HTML:

php
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::mask()

Str::mask 方法用重复字符掩盖字符串的一部分,可以用于模糊化电子邮件地址和电话号码等字符串段:

php
use Illuminate\Support\Str;

$string = Str::mask('taylor@example.com', '*', 3);

// tay***************

如果需要,您可以将负数作为 mask 方法的第三个参数传递,这将指示方法从字符串末尾的给定距离开始掩盖:

php
$string = Str::mask('taylor@example.com', '*', -15, 3);

// tay***@example.com

Str::orderedUuid()

Str::orderedUuid 方法生成一个“时间戳优先”的 UUID,可以有效地存储在索引数据库列中。使用此方法生成的每个 UUID 都将按顺序排列在之前生成的 UUID 之后:

php
use Illuminate\Support\Str;

return (string) Str::orderedUuid();

Str::padBoth()

Str::padBoth 方法包装 PHP 的 str_pad 函数,用另一个字符串填充字符串的两侧,直到最终字符串达到所需长度:

php
use Illuminate\Support\Str;

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

// '__James___'

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

// '  James   '

Str::padLeft()

Str::padLeft 方法包装 PHP 的 str_pad 函数,用另一个字符串填充字符串的左侧,直到最终字符串达到所需长度:

php
use Illuminate\Support\Str;

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

// '-=-=-James'

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

// '     James'

Str::padRight()

Str::padRight 方法包装 PHP 的 str_pad 函数,用另一个字符串填充字符串的右侧,直到最终字符串达到所需长度:

php
use Illuminate\Support\Str;

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

// 'James-----'

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

// 'James     '

Str::plural()

Str::plural 方法将单数单词字符串转换为其复数形式。此函数支持 Laravel 复数化器支持的任何语言

php
use Illuminate\Support\Str;

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

// cars

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

// children

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

php
use Illuminate\Support\Str;

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

// children

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

// child

Str::pluralStudly()

Str::pluralStudly 方法将以 StudlyCaps 格式的单数单词字符串转换为其复数形式。此函数支持 Laravel 复数化器支持的任何语言

php
use Illuminate\Support\Str;

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

// VerifiedHumans

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

// UserFeedback

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

php
use Illuminate\Support\Str;

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

// VerifiedHumans

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

// VerifiedHuman

Str::random()

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

php
use Illuminate\Support\Str;

$random = Str::random(40);

Str::remove()

Str::remove 方法从字符串中移除给定值或值数组:

php
use Illuminate\Support\Str;

$string = 'Peter Piper picked a peck of pickled peppers.';

$removed = Str::remove('e', $string);

// Ptr Pipr pickd a pck of pickld ppprs.

您还可以将 false 作为 remove 方法的第三个参数传递,以在移除字符串时忽略大小写。

Str::replace()

Str::replace 方法替换字符串中的给定字符串:

php
use Illuminate\Support\Str;

$string = 'Laravel 8.x';

$replaced = Str::replace('8.x', '9.x', $string);

// Laravel 9.x

Str::replaceArray()

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

php
use Illuminate\Support\Str;

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

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

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

Str::replaceFirst()

Str::replaceFirst 方法替换字符串中给定值的第一次出现:

php
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()

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

php
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::reverse()

Str::reverse 方法反转给定字符串:

php
use Illuminate\Support\Str;

$reversed = Str::reverse('Hello World');

// dlroW olleH

Str::singular()

Str::singular 方法将字符串转换为其单数形式。此函数支持 Laravel 复数化器支持的任何语言

php
use Illuminate\Support\Str;

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

// car

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

// child

Str::slug()

Str::slug 方法从给定字符串生成 URL 友好的“slug”:

php
use Illuminate\Support\Str;

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

// laravel-5-framework

Str::snake()

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

php
use Illuminate\Support\Str;

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

// foo_bar

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

// foo-bar

Str::squish()

Str::squish 方法从字符串中移除所有多余的空白,包括单词之间的多余空白:

php
use Illuminate\Support\Str;

$string = Str::squish('    laravel    framework    ');

// laravel framework

Str::start()

Str::start 方法在字符串开头添加给定值的单个实例,如果字符串尚未以该值开头:

php
use Illuminate\Support\Str;

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

// /this/string

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

// /this/string

Str::startsWith()

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

php
use Illuminate\Support\Str;

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

// true

如果传递了可能值的数组,则 startsWith 方法将在字符串以任何给定值开头时返回 true

php
$result = Str::startsWith('This is my name', ['This', 'That', 'There']);

// true

Str::studly()

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

php
use Illuminate\Support\Str;

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

// FooBar

Str::substr()

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

php
use Illuminate\Support\Str;

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

// Laravel

Str::substrCount()

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

php
use Illuminate\Support\Str;

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

// 2

Str::substrReplace()

Str::substrReplace 方法替换字符串中由第三个参数指定的位置内的文本,并替换由第四个参数指定的字符数。将 0 传递给方法的第四个参数将在指定位置插入字符串,而不替换字符串中的任何现有字符:

php
use Illuminate\Support\Str;

$result = Str::substrReplace('1300', ':', 2);
// 13:

$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00

Str::swap()

Str::swap 方法使用 PHP 的 strtr 函数替换给定字符串中的多个值:

php
use Illuminate\Support\Str;

$string = Str::swap([
    'Tacos' => 'Burritos',
    'great' => 'fantastic',
], 'Tacos are great!');

// Burritos are fantastic!

Str::title()

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

php
use Illuminate\Support\Str;

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

// A Nice Title Uses The Correct Case

Str::toHtmlString()

Str::toHtmlString 方法将字符串实例转换为 Illuminate\Support\HtmlString 的实例,可以在 Blade 模板中显示:

php
use Illuminate\Support\Str;

$htmlString = Str::of('Nuno Maduro')->toHtmlString();

Str::ucfirst()

Str::ucfirst 方法返回首字母大写的给定字符串:

php
use Illuminate\Support\Str;

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

// Foo bar

Str::ucsplit()

Str::ucsplit 方法通过大写字符将给定字符串拆分为数组:

php
use Illuminate\Support\Str;

$segments = Str::ucsplit('FooBar');

// [0 => 'Foo', 1 => 'Bar']

Str::upper()

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

php
use Illuminate\Support\Str;

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

// LARAVEL

Str::ulid()

Str::ulid 方法生成一个 ULID:

php
use Illuminate\Support\Str;

return (string) Str::ulid();

// 01gd6r360bp37zj17nxb55yv40

Str::uuid()

Str::uuid 方法生成一个 UUID(版本 4):

php
use Illuminate\Support\Str;

return (string) Str::uuid();

Str::wordCount()

Str::wordCount 方法返回字符串中包含的单词数:

php
use Illuminate\Support\Str;

Str::wordCount('Hello, world!'); // 2

Str::words()

Str::words 方法限制字符串中的单词数量。可以通过其第三个参数传递附加字符串,以指定应附加到截断字符串末尾的字符串:

php
use Illuminate\Support\Str;

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

// Perfectly balanced, as >>>

str()

str 函数返回给定字符串的新的 Illuminate\Support\Stringable 实例。此函数等效于 Str::of 方法:

php
$string = str('Taylor')->append(' Otwell');

// 'Taylor Otwell'

如果未提供参数给 str 函数,该函数将返回 Illuminate\Support\Str 的实例:

php
$snake = str()->snake('FooBar');

// 'foo_bar'

trans()

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

php
echo trans('messages.welcome');

如果指定的翻译键不存在,trans 函数将返回给定的键。因此,使用上面的示例,如果翻译键不存在,trans 函数将返回 messages.welcome

trans_choice()

trans_choice 函数使用屈折翻译给定的翻译键:

php
echo trans_choice('messages.notifications', $unreadCount);

如果指定的翻译键不存在,trans_choice 函数将返回给定的键。因此,使用上面的示例,如果翻译键不存在,trans_choice 函数将返回 messages.notifications

流畅字符串

流畅字符串为处理字符串值提供了更流畅的面向对象接口,允许您使用比传统字符串操作更具可读性的语法来链接多个字符串操作。

after

after 方法返回字符串中给定值之后的所有内容。如果该值不在字符串中,则返回整个字符串:

php
use Illuminate\Support\Str;

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

// ' my name'

afterLast

afterLast 方法返回字符串中最后一次出现的给定值之后的所有内容。如果该值不在字符串中,则返回整个字符串:

php
use Illuminate\Support\Str;

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

// 'Controller'

append

append 方法将给定值附加到字符串:

php
use Illuminate\Support\Str;

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

// 'Taylor Otwell'

ascii

ascii 方法将尝试将字符串音译为 ASCII 值:

php
use Illuminate\Support\Str;

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

// 'u'

basename

basename 方法将返回给定字符串的尾部名称组件:

php
use Illuminate\Support\Str;

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

// 'baz'

如果需要,您可以提供一个将从尾部组件中移除的“扩展名”:

php
use Illuminate\Support\Str;

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

// 'baz'

before

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

php
use Illuminate\Support\Str;

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

// 'This is '

beforeLast

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

php
use Illuminate\Support\Str;

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

// 'This '

between

between 方法返回两个值之间的字符串部分:

php
use Illuminate\Support\Str;

$converted = Str::of('This is my name')->between('This', 'name');

// ' is my '

betweenFirst

betweenFirst 方法返回两个值之间的最小可能字符串部分:

php
use Illuminate\Support\Str;

$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');

// 'a'

camel

camel 方法将给定字符串转换为 camelCase

php
use Illuminate\Support\Str;

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

// fooBar

classBasename

classBasename 方法返回给定类的类名,并移除类的命名空间:

php
use Illuminate\Support\Str;

$class = Str::of('Foo\Bar\Baz')->classBasename();

// Baz

contains

contains 方法确定给定字符串是否包含给定值。此方法区分大小写:

php
use Illuminate\Support\Str;

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

// true

您还可以传递值数组以确定给定字符串是否包含数组中的任何值:

php
use Illuminate\Support\Str;

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

// true

containsAll

containsAll 方法确定给定字符串是否包含给定数组中的所有值:

php
use Illuminate\Support\Str;

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

// true

dirname

dirname 方法返回给定字符串的父目录部分:

php
use Illuminate\Support\Str;

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

// '/foo/bar'

如果需要,您可以指定要从字符串中修剪的目录级别数:

php
use Illuminate\Support\Str;

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

// '/foo'

excerpt

excerpt 方法从字符串中提取与该字符串中短语的第一次出现匹配的摘录:

php
use Illuminate\Support\Str;

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

// '...is my na...'

radius 选项默认为 100,允许您定义截断字符串两侧应出现的字符数。

此外,您可以使用 omission 选项更改将附加到截断字符串的字符串:

php
use Illuminate\Support\Str;

$excerpt = Str::of('This is my name')->excerpt('name', [
    'radius' => 3,
    'omission' => '(...) '
]);

// '(...) my name'

endsWith

endsWith 方法确定给定字符串是否以给定值结尾:

php
use Illuminate\Support\Str;

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

// true

您还可以传递值数组以确定给定字符串是否以数组中的任何值结尾:

php
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

exactly 方法确定给定字符串是否与另一个字符串完全匹配:

php
use Illuminate\Support\Str;

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

// true

explode

explode 方法通过给定的分隔符拆分字符串,并返回包含拆分字符串每个部分的集合:

php
use Illuminate\Support\Str;

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

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

finish

finish 方法在字符串末尾添加给定值的单个实例,如果字符串尚未以该值结尾:

php
use Illuminate\Support\Str;

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

// this/string/

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

// this/string/

headline

headline 方法将由大小写、连字符或下划线分隔的字符串转换为以空格分隔的字符串,并将每个单词的首字母大写:

php
use Illuminate\Support\Str;

$headline = Str::of('taylor_otwell')->headline();

// Taylor Otwell

$headline = Str::of('EmailNotificationSent')->headline();

// Email Notification Sent

inlineMarkdown

inlineMarkdown 方法使用 CommonMark 将 GitHub 风格的 Markdown 转换为内联 HTML。然而,与 markdown 方法不同,它不会将所有生成的 HTML 包裹在块级元素中:

php
use Illuminate\Support\Str;

$html = Str::of('**Laravel**')->inlineMarkdown();

// <strong>Laravel</strong>

is

is 方法确定给定字符串是否与给定模式匹配。星号可以用作通配符:

php
use Illuminate\Support\Str;

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

// true

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

// false

isAscii

isAscii 方法确定给定字符串是否为 ASCII 字符串:

php
use Illuminate\Support\Str;

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

// true

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

// false

isEmpty

isEmpty 方法确定给定字符串是否为空:

php
use Illuminate\Support\Str;

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

// true

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

// false

isNotEmpty

isNotEmpty 方法确定给定字符串是否不为空:

php
use Illuminate\Support\Str;

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

// false

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

// true

isJson

isJson 方法确定给定字符串是否为有效的 JSON:

php
use Illuminate\Support\Str;

$result = Str::of('[1,2,3]')->isJson();

// true

$result = Str::of('{"first": "John", "last": "Doe"}')->isJson();

// true

$result = Str::of('{first: "John", last: "Doe"}')->isJson();

// false

isUlid

isUlid 方法确定给定字符串是否为 ULID:

php
use Illuminate\Support\Str;

$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();

// true

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

// false

isUuid

isUuid 方法确定给定字符串是否为 UUID:

php
use Illuminate\Support\Str;

$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();

// true

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

// false

kebab

kebab 方法将给定字符串转换为 kebab-case

php
use Illuminate\Support\Str;

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

// foo-bar

lcfirst

lcfirst 方法返回首字母小写的给定字符串:

php
use Illuminate\Support\Str;

$string = Str::of('Foo Bar')->lcfirst();

// foo Bar

length

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

php
use Illuminate\Support\Str;

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

// 7

limit

limit 方法将给定字符串截断为指定长度:

php
use Illuminate\Support\Str;

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

// The quick brown fox...

您还可以传递第二个参数来更改将在截断字符串末尾附加的字符串:

php
use Illuminate\Support\Str;

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

// The quick brown fox (...)

lower

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

php
use Illuminate\Support\Str;

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

// 'laravel'

ltrim

ltrim 方法修剪字符串的左侧:

php
use Illuminate\Support\Str;

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

// 'Laravel  '

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

// 'Laravel/'

markdown

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

php
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>

mask

mask 方法用重复字符掩盖字符串的一部分,可以用于模糊化电子邮件地址和电话号码等字符串段:

php
use Illuminate\Support\Str;

$string = Str::of('taylor@example.com')->mask('*', 3);

// tay***************

如果需要,您可以将负数作为 mask 方法的第三个或第四个参数传递,这将指示方法从字符串末尾的给定距离开始掩盖:

php
$string = Str::of('taylor@example.com')->mask('*', -15, 3);

// tay***@example.com

$string = Str::of('taylor@example.com')->mask('*', 4, -4);

// tayl**********.com

match

match 方法将返回与给定正则表达式模式匹配的字符串部分:

php
use Illuminate\Support\Str;

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

// 'bar'

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

// 'bar'

matchAll

matchAll 方法将返回包含与给定正则表达式模式匹配的字符串部分的集合:

php
use Illuminate\Support\Str;

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

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

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

php
use Illuminate\Support\Str;

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

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

如果未找到匹配项,将返回空集合。

newLine

newLine 方法在字符串末尾附加一个“行尾”字符:

php
use Illuminate\Support\Str;

$padded = Str::of('Laravel')->newLine()->append('Framework');

// 'Laravel
//  Framework'

padBoth

padBoth 方法包装 PHP 的 str_pad 函数,用另一个字符串填充字符串的两侧,直到最终字符串达到所需长度:

php
use Illuminate\Support\Str;

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

// '__James___'

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

// '  James   '

padLeft

padLeft 方法包装 PHP 的 str_pad 函数,用另一个字符串填充字符串的左侧,直到最终字符串达到所需长度:

php
use Illuminate\Support\Str;

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

// '-=-=-James'

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

// '     James'

padRight

padRight 方法包装 PHP 的 str_pad 函数,用另一个字符串填充字符串的右侧,直到最终字符串达到所需长度:

php
use Illuminate\Support\Str;

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

// 'James-----'

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

// 'James     '

pipe

pipe 方法允许您通过将其当前值传递给给定的可调用对象来转换字符串:

php
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

plural 方法将单数单词字符串转换为其复数形式。此函数支持 Laravel 复数化器支持的任何语言

php
use Illuminate\Support\Str;

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

// cars

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

// children

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

php
use Illuminate\Support\Str;

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

// children

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

// child

prepend

prepend 方法将给定值附加到字符串:

php
use Illuminate\Support\Str;

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

// Laravel Framework

remove

remove 方法从字符串中移除给定值或值数组:

php
use Illuminate\Support\Str;

$string = Str::of('Arkansas is quite beautiful!')->remove('quite');

// Arkansas is beautiful!

您还可以将 false 作为第二个参数传递,以在移除字符串时忽略大小写。

replace

replace 方法替换字符串中的给定字符串:

php
use Illuminate\Support\Str;

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

// Laravel 7.x

replaceArray

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

php
use Illuminate\Support\Str;

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

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

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

replaceFirst

replaceFirst 方法替换字符串中给定值的第一次出现:

php
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 方法替换字符串中给定值的最后一次出现:

php
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 方法用给定的替换字符串替换字符串中所有匹配模式的部分:

php
use Illuminate\Support\Str;

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

// '15015551000'

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

php
use Illuminate\Support\Str;

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

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

rtrim

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

php
use Illuminate\Support\Str;

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

// '  Laravel'

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

// '/Laravel'

scan

scan 方法根据 sscanf PHP 函数 支持的格式从字符串中解析输入为集合:

php
use Illuminate\Support\Str;

$collection = Str::of('filename.jpg')->scan('%[^.].%s');

// collect(['filename', 'jpg'])

singular

singular 方法将字符串转换为其单数形式。此函数支持 Laravel 复数化器支持的任何语言

php
use Illuminate\Support\Str;

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

// car

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

// child

slug

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

php
use Illuminate\Support\Str;

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

// laravel-framework

snake

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

php
use Illuminate\Support\Str;

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

// foo_bar

split

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

php
use Illuminate\Support\Str;

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

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

squish

squish 方法从字符串中移除所有多余的空白,包括单词之间的多余空白:

php
use Illuminate\Support\Str;

$string = Str::of('    laravel    framework    ')->squish();

// laravel framework

start

start 方法在字符串的开头添加给定值的单个实例(如果它尚未以该值开头):

php
use Illuminate\Support\Str;

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

// /this/string

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

// /this/string

startsWith

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

php
use Illuminate\Support\Str;

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

// true

studly

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

php
use Illuminate\Support\Str;

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

// FooBar

substr

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

php
use Illuminate\Support\Str;

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

// Framework

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

// Frame

substrReplace

substrReplace 方法替换字符串中指定位置的文本,并替换由第三个参数指定的字符数。将 0 传递给方法的第三个参数将在指定位置插入字符串,而不替换字符串中的任何现有字符:

php
use Illuminate\Support\Str;

$string = Str::of('1300')->substrReplace(':', 2);

// 13:

$string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0);

// The Laravel Framework

swap

swap 方法使用 PHP 的 strtr 函数替换字符串中的多个值:

php
use Illuminate\Support\Str;

$string = Str::of('Tacos are great!')
    ->swap([
        'Tacos' => 'Burritos',
        'great' => 'fantastic',
    ]);

// Burritos are fantastic!

tap

tap 方法将字符串传递给给定的闭包,允许您检查和操作字符串,而不影响字符串本身。无论闭包返回什么,tap 方法都会返回原始字符串:

php
use Illuminate\Support\Str;

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

// LARAVEL FRAMEWORK

test

test 方法确定字符串是否匹配给定的正则表达式模式:

php
use Illuminate\Support\Str;

$result = Str::of('Laravel Framework')->test('/Laravel/');

// true

title

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

php
use Illuminate\Support\Str;

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

// A Nice Title Uses The Correct Case

trim

trim 方法修剪给定字符串:

php
use Illuminate\Support\Str;

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

// 'Laravel'

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

// 'Laravel'

ucfirst

ucfirst 方法返回首字母大写的给定字符串:

php
use Illuminate\Support\Str;

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

// Foo bar

ucsplit

ucsplit 方法按大写字符将给定字符串拆分为集合:

php
use Illuminate\Support\Str;

$string = Str::of('Foo Bar')->ucsplit();

// collect(['Foo', 'Bar'])

upper

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

php
use Illuminate\Support\Str;

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

// LARAVEL

when

when 方法在给定条件为 true 时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

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

// 'Taylor Otwell'

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

whenContains

whenContains 方法在字符串包含给定值时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('tony stark')
            ->whenContains('tony', function ($string) {
                return $string->title();
            });

// 'Tony Stark'

如果需要,您可以将另一个闭包作为第三个参数传递给 when 方法。如果字符串不包含给定值,则此闭包将执行。

您还可以传递一个值数组,以确定给定字符串是否包含数组中的任何值:

php
use Illuminate\Support\Str;

$string = Str::of('tony stark')
            ->whenContains(['tony', 'hulk'], function ($string) {
                return $string->title();
            });

// Tony Stark

whenContainsAll

whenContainsAll 方法在字符串包含所有给定子字符串时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('tony stark')
                ->whenContainsAll(['tony', 'stark'], function ($string) {
                    return $string->title();
                });

// 'Tony Stark'

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

whenEmpty

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

php
use Illuminate\Support\Str;

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

// 'Laravel'

whenNotEmpty

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

php
use Illuminate\Support\Str;

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

// 'Laravel Framework'

whenStartsWith

whenStartsWith 方法在字符串以给定子字符串开头时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('disney world')->whenStartsWith('disney', function ($string) {
    return $string->title();
});

// 'Disney World'

whenEndsWith

whenEndsWith 方法在字符串以给定子字符串结尾时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('disney world')->whenEndsWith('world', function ($string) {
    return $string->title();
});

// 'Disney World'

whenExactly

whenExactly 方法在字符串与给定字符串完全匹配时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('laravel')->whenExactly('laravel', function ($string) {
    return $string->title();
});

// 'Laravel'

whenNotExactly

whenNotExactly 方法在字符串与给定字符串不完全匹配时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('framework')->whenNotExactly('laravel', function ($string) {
    return $string->title();
});

// 'Framework'

whenIs

whenIs 方法在字符串匹配给定模式时调用给定的闭包。星号可以用作通配符。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('foo/bar')->whenIs('foo/*', function ($string) {
    return $string->append('/baz');
});

// 'foo/bar/baz'

whenIsAscii

whenIsAscii 方法在字符串为 7 位 ASCII 时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('laravel')->whenIsAscii(function ($string) {
    return $string->title();
});

// 'Laravel'

whenIsUlid

whenIsUlid 方法在字符串为有效的 ULID 时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function ($string) {
    return $string->substr(0, 8);
});

// '01gd6r36'

whenIsUuid

whenIsUuid 方法在字符串为有效的 UUID 时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function ($string) {
    return $string->substr(0, 8);
});

// 'a0a2a2d2'

whenTest

whenTest 方法在字符串匹配给定正则表达式时调用给定的闭包。闭包将接收流畅的字符串实例:

php
use Illuminate\Support\Str;

$string = Str::of('laravel framework')->whenTest('/laravel/', function ($string) {
    return $string->title();
});

// 'Laravel Framework'

wordCount

wordCount 方法返回字符串包含的单词数:

php
use Illuminate\Support\Str;

Str::of('Hello, world!')->wordCount(); // 2

words

words 方法限制字符串中的单词数量。如果需要,您可以指定一个附加字符串,该字符串将附加到截断的字符串:

php
use Illuminate\Support\Str;

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

// Perfectly balanced, as >>>

URLs

action()

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

php
use App\Http\Controllers\HomeController;

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

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

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

asset()

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

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

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

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

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

route()

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

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

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

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

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

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

secure_asset()

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

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

secure_url()

secure_url 函数为给定路径生成完全合格的 HTTPS URL。可以在函数的第二个参数中传递附加的 URL 段:

php
$url = secure_url('user/profile');

$url = secure_url('user/profile', [1]);

to_route()

to_route 函数为给定的 命名路由 生成 重定向 HTTP 响应

php
return to_route('users.show', ['user' => 1]);

如果需要,您可以将应分配给重定向的 HTTP 状态码和任何附加的响应头作为第三个和第四个参数传递给 to_route 方法:

php
return to_route('users.show', ['user' => 1], 302, ['X-Framework' => 'Laravel']);

url()

url 函数为给定路径生成完全合格的 URL:

php
$url = url('user/profile');

$url = url('user/profile', [1]);

如果未提供路径,则返回 Illuminate\Routing\UrlGenerator 实例:

php
$current = url()->current();

$full = url()->full();

$previous = url()->previous();

杂项

abort()

abort 函数抛出 HTTP 异常,该异常将由 异常处理程序 渲染:

php
abort(403);

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

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

abort_if()

abort_if 函数在给定的布尔表达式计算为 true 时抛出 HTTP 异常:

php
abort_if(! Auth::user()->isAdmin(), 403);

abort 方法一样,您还可以将异常的响应文本作为第三个参数提供,并将自定义响应头数组作为第四个参数传递给函数。

abort_unless()

abort_unless 函数在给定的布尔表达式计算为 false 时抛出 HTTP 异常:

php
abort_unless(Auth::user()->isAdmin(), 403);

abort 方法一样,您还可以将异常的响应文本作为第三个参数提供,并将自定义响应头数组作为第四个参数传递给函数。

app()

app 函数返回 服务容器 实例:

php
$container = app();

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

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

auth()

auth 函数返回 认证器 实例。您可以将其用作 Auth facade 的替代方法:

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

如果需要,您可以指定要访问的守卫实例:

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

back()

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

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

return back();

bcrypt()

bcrypt 函数使用 Bcrypt 哈希 给定值。您可以将此函数用作 Hash facade 的替代方法:

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

blank()

blank 函数确定给定值是否为 "blank":

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

// true

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

// false

有关 blank 的反义词,请参见 filled 方法。

broadcast()

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

php
broadcast(new UserRegistered($user));

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

cache()

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

php
$value = cache('key');

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

您可以通过将键/值对数组传递给函数来将项目添加到缓存中。您还应该传递缓存值应被视为有效的秒数或持续时间:

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

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

class_uses_recursive()

class_uses_recursive 函数返回类使用的所有特性,包括其所有父类使用的特性:

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

collect()

collect 函数从给定值创建 集合 实例:

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

config()

config 函数获取 配置 变量的值。可以使用 "点" 语法访问配置值,其中包括要访问的文件名和选项。可以指定默认值,如果配置选项不存在,则返回该值:

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

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

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

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

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

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

csrf_field()

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

php
{{ csrf_field() }}

csrf_token()

csrf_token 函数检索当前 CSRF 令牌的值:

php
$token = csrf_token();

decrypt()

decrypt 函数 解密 给定值。您可以将此函数用作 Crypt facade 的替代方法:

php
$password = decrypt($value);

dd()

dd 函数转储给定变量并结束脚本的执行:

php
dd($value);

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

如果您不想在转储变量后停止执行脚本,请使用 dump 函数。

dispatch()

dispatch 函数将给定的 作业 推送到 Laravel 作业队列

php
dispatch(new App\Jobs\SendEmails);

dump()

dump 函数转储给定变量:

php
dump($value);

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

如果您想在转储变量后停止执行脚本,请使用 dd 函数。

encrypt()

encrypt 函数 加密 给定值。您可以将此函数用作 Crypt facade 的替代方法:

php
$secret = encrypt('my-secret-value');

env()

env 函数检索 环境变量 的值或返回默认值:

php
$env = env('APP_ENV');

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

如果您在部署过程中执行 config:cache 命令,您应确保仅在配置文件中调用 env 函数。一旦配置被缓存,.env 文件将不会被加载,所有对 env 函数的调用将返回 null

event()

event 函数将给定的 事件 分派给其监听器:

php
event(new UserRegistered($user));

fake()

fake 函数从容器中解析一个 Faker 单例,这在创建模型工厂、数据库填充、测试和原型视图中的假数据时非常有用:

blade
@for($i = 0; $i < 10; $i++)
    <dl>
        <dt>Name</dt>
        <dd>{{ fake()->name() }}</dd>

        <dt>Email</dt>
        <dd>{{ fake()->unique()->safeEmail() }}</dd>
    </dl>
@endfor

默认情况下,fake 函数将使用 config/app.php 配置文件中的 app.faker_locale 配置选项;但是,您也可以通过将其传递给 fake 函数来指定区域设置。每个区域设置将解析一个单独的单例:

php
fake('nl_NL')->name()

filled()

filled 函数确定给定值是否不为 "blank":

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

// true

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

// false

有关 filled 的反义词,请参见 blank 方法。

info()

info 函数将信息写入应用程序的 日志

php
info('Some helpful information!');

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

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

logger()

logger 函数可用于将 debug 级别消息写入 日志

php
logger('Debug message');

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

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

如果未传递任何值给函数,将返回 logger 实例:

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

method_field()

method_field 函数生成一个包含表单 HTTP 动词伪造值的 HTML hidden 输入字段。例如,使用 Blade 语法

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

now()

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

php
$now = now();

old()

old 函数 检索 闪存到会话中的 旧输入 值:

php
$value = old('value');

$value = old('value', 'default');

由于作为 old 函数的第二个参数提供的 "默认值" 通常是 Eloquent 模型的属性,Laravel 允许您简单地将整个 Eloquent 模型作为 old 函数的第二个参数传递。这样做时,Laravel 将假定提供给 old 函数的第一个参数是应视为 "默认值" 的 Eloquent 属性的名称:

php
{{ old('name', $user->name) }}

// 等同于...

{{ old('name', $user) }}

optional()

optional 函数接受任何参数,并允许您访问该对象的属性或调用方法。如果给定对象为 null,则属性和方法将返回 null,而不是导致错误:

php
return optional($user->address)->street;

{!! old('name', optional($user)->name) !!}

optional 函数还接受闭包作为其第二个参数。如果作为第一个参数提供的值不为 null,则将调用闭包:

php
return optional(User::find($id), function ($user) {
    return $user->name;
});

policy()

policy 方法检索给定类的 策略 实例:

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

redirect()

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

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

return redirect('/home');

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

report()

report 函数将使用您的 异常处理程序 报告异常:

php
report($e);

report 函数还接受字符串作为参数。当字符串传递给函数时,函数将创建一个带有给定字符串作为其消息的异常:

php
report('Something went wrong.');

report_if()

report_if 函数将在给定条件为 true 时使用您的 异常处理程序 报告异常:

php
report_if($shouldReport, $e);

report_if($shouldReport, 'Something went wrong.');

report_unless()

report_unless 函数将在给定条件为 false 时使用您的 异常处理程序 报告异常:

php
report_unless($reportingDisabled, $e);

report_unless($reportingDisabled, 'Something went wrong.');

request()

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

php
$request = request();

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

rescue()

rescue 函数执行给定的闭包,并捕获其执行期间发生的任何异常。所有被捕获的异常将发送到您的 异常处理程序;然而,请求将继续处理:

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

您还可以将第二个参数传递给 rescue 函数。此参数将是如果在执行闭包时发生异常时应返回的 "默认" 值:

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

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

resolve()

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

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

response()

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

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

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

retry()

retry 函数尝试执行给定的回调,直到达到给定的最大尝试阈值。如果回调未抛出异常,则返回其返回值。如果回调抛出异常,则会自动重试。如果超过最大尝试次数,则抛出异常:

php
return retry(5, function () {
    // 尝试 5 次,每次尝试之间休息 100 毫秒...
}, 100);

如果您希望手动计算每次尝试之间的毫秒数,可以将闭包作为第三个参数传递给 retry 函数:

php
return retry(5, function () {
    // ...
}, function ($attempt, $exception) {
    return $attempt * 100;
});

为了方便起见,您可以将数组作为 retry 函数的第一个参数提供。此数组将用于确定后续尝试之间的休眠毫秒数:

php
return retry([100, 200], function () {
    // 第一次重试休眠 100 毫秒,第二次重试休眠 200 毫秒...
});

要仅在特定条件下重试,您可以将闭包作为第四个参数传递给 retry 函数:

php
return retry(5, function () {
    // ...
}, 100, function ($exception) {
    return $exception instanceof RetryException;
});

session()

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

php
$value = session('key');

您可以通过将键/值对数组传递给函数来设置值:

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

如果未传递任何值给函数,将返回会话存储:

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

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

tap()

tap 函数接受两个参数:任意 $value 和一个闭包。$value 将传递给闭包,然后由 tap 函数返回。闭包的返回值无关紧要:

php
$user = tap(User::first(), function ($user) {
    $user->name = 'taylor';

    $user->save();
});

如果未将闭包传递给 tap 函数,您可以在给定的 $value 上调用任何方法。您调用的方法的返回值将始终是 $value,无论方法在其定义中实际返回什么。例如,Eloquent update 方法通常返回一个整数。然而,我们可以通过 tap 函数链式调用 update 方法来强制方法返回模型本身:

php
$user = tap($user)->update([
    'name' => $name,
    'email' => $email,
]);

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

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

throw_if()

throw_if 函数在给定的布尔表达式计算为 true 时抛出给定的异常:

php
throw_if(! Auth::user()->isAdmin(), AuthorizationException::class);

throw_if(
    ! Auth::user()->isAdmin(),
    AuthorizationException::class,
    'You are not allowed to access this page.'
);

throw_unless()

throw_unless 函数在给定的布尔表达式计算为 false 时抛出给定的异常:

php
throw_unless(Auth::user()->isAdmin(), AuthorizationException::class);

throw_unless(
    Auth::user()->isAdmin(),
    AuthorizationException::class,
    'You are not allowed to access this page.'
);

today()

today 函数为当前日期创建一个新的 Illuminate\Support\Carbon 实例:

php
$today = today();

trait_uses_recursive()

trait_uses_recursive 函数返回特性使用的所有特性:

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

transform()

transform 函数在给定值不为 blank 时执行闭包,然后返回闭包的返回值:

php
$callback = function ($value) {
    return $value * 2;
};

$result = transform(5, $callback);

// 10

可以将默认值或闭包作为第三个参数传递给函数。如果给定值为空,则返回此值:

php
$result = transform(null, $callback, 'The value is blank');

// The value is blank

validator()

validator 函数使用给定参数创建一个新的 验证器 实例。您可以将其用作 Validator facade 的替代方法:

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

value()

value 函数返回给定的值。然而,如果您将闭包传递给函数,则会执行闭包并返回其返回值:

php
$result = value(true);

// true

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

// false

可以将附加参数传递给 value 函数。如果第一个参数是闭包,则附加参数将作为参数传递给闭包,否则将被忽略:

php
$result = value(function ($name) {
    return $parameter;
}, 'Taylor');

// 'Taylor'

view()

view 函数检索 视图 实例:

php
return view('auth.login');

with()

with 函数返回给定的值。如果将闭包作为函数的第二个参数传递,则会执行闭包并返回其返回值:

php
$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

其他实用工具

基准测试

有时您可能希望快速测试应用程序某些部分的性能。在这些情况下,您可以利用 Benchmark 支持类来测量给定回调完成所需的毫秒数:

php
<?php

use App\Models\User;
use Illuminate\Support\Benchmark;

Benchmark::dd(fn () => User::find(1)); // 0.1 ms

Benchmark::dd([
    'Scenario 1' => fn () => User::count(), // 0.5 ms
    'Scenario 2' => fn () => User::all()->count(), // 20.0 ms
]);

默认情况下,给定的回调将执行一次(一次迭代),其持续时间将显示在浏览器/控制台中。

要多次调用回调,您可以将回调应调用的迭代次数作为方法的第二个参数指定。当多次执行回调时,Benchmark 类将返回在所有迭代中执行回调所需的平均毫秒数:

php
Benchmark::dd(fn () => User::count(), iterations: 10); // 0.5 ms

彩票

Laravel 的彩票类可用于根据给定的几率执行回调。这在您只希望为一定比例的传入请求执行代码时特别有用:

php
use Illuminate\Support\Lottery;

Lottery::odds(1, 20)
    ->winner(fn () => $user->won())
    ->loser(fn () => $user->lost())
    ->choose();

您可以将 Laravel 的彩票类与其他 Laravel 功能结合使用。例如,您可能希望仅向异常处理程序报告一小部分慢查询。并且,由于彩票类是可调用的,我们可以将类的实例传递给任何接受可调用的方法:

php
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Lottery;

DB::whenQueryingForLongerThan(
    CarbonInterval::seconds(2),
    Lottery::odds(1, 100)->winner(fn () => report('Querying > 2 seconds.')),
);

测试彩票

Laravel 提供了一些简单的方法,允许您轻松测试应用程序的彩票调用:

php
// 彩票将始终获胜...
Lottery::alwaysWin();

// 彩票将始终失败...
Lottery::alwaysLose();

// 彩票将获胜然后失败,最后恢复正常行为...
Lottery::fix([true, false]);

// 彩票将恢复正常行为...
Lottery::determineResultsNormally();