辅助函数


简介

Laravel 自带了一系列 PHP 辅助函数,很多被框架自身使用,如果你觉得方便的话也可以在代码中使用它们。

方法列表

数组 & 对象

Arr::accessible()

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

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

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

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

Arr::divide 方法返回两个数组,一个包含原数组的所有键,另外一个包含原数组的所有值:

use Illuminate\Support\Arr;

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

// $keys: ['name']

// $values: ['Desk']

Arr::dot()

Arr::dot 方法使用「.」号将将多维数组转化为一维数组:

use Illuminate\Support\Arr;

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

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

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

Arr::except()

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

use Illuminate\Support\Arr;

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

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

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

Arr::exists()

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

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

Arr::flatten 方法将多维数组转化为一维数组:

use Illuminate\Support\Arr;

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

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

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

Arr::forget()

Arr::forget 方法使用「.」号从嵌套数组中移除给定键值对:

use Illuminate\Support\Arr;

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

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

// ['products' => []]

Arr::get()

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

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

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

Arr::isAssoc() 方法会在给定数组是关联数组时返回 true,如果一个数组没有包含从0开始的数字序列键,就被认为是「关联数组」:

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,如果给定数组的键是以零开始的连续整数:

use Illuminate\Support\Arr;
 
$isList = Arr::isList(['foo', 'bar', 'baz']);
 
// true
 
$isList = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]);
 
// false

Arr::join()

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

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 方法将数组按给定的键进行键名。如果多个项具有相同的键,新数组中只会出现最后一个项:

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 方法返回通过过滤数组的最后一个元素:

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::map()

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

use Illuminate\Support\Arr;
 
$array = ['first' => 'james', 'last' => 'kirk'];
 
$mapped = Arr::map($array, function (string $value, string $key) {
    return ucfirst($value);
});
 
// ['first' => 'James', 'last' => 'Kirk']

Arr::mapWithKeys()

Arr::mapWithKeys 方法遍历数组并将每个值传递给给定的回调函数。回调函数应返回一个包含单个键值对的关联数组:

use Illuminate\Support\Arr;
 
$array = [
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => 'john@example.com',
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => 'jane@example.com',
    ]
];
 
$mapped = Arr::mapWithKeys($array, function (array $item, int $key) {
    return [$item['email'] => $item['name']];
});
 
/*
    [
        'john@example.com' => 'John',
        'jane@example.com' => 'Jane',
    ]
*/

Arr::only()

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

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

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::prependKeysWith()

Arr::prependKeysWith 函数会在关联数组的所有键名前添加指定的前缀:

use Illuminate\Support\Arr;
 
$array = [
    'name' => 'Desk',
    'price' => 100,
];
 
$keyed = Arr::prependKeysWith($array, 'product.');
 
/*
    [
        'product.name' => 'Desk',
        'product.price' => 100,
    ]
*/

Arr::pull()

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

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

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

Arr::set 方法用于在嵌套数组中使用「.」号设置值:

use Illuminate\Support\Arr;

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

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

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

Arr::shuffle()

Arr::shuffle() 方法会随机打乱数组中元素的排序:

use Illuminate\Support\Arr;

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

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

Arr::sort()

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

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

use Illuminate\Support\Arr;
 
$array = ['Desk', 'Table', 'Chair'];
 
$sorted = Arr::sortDesc($array);
 
// ['Table', 'Desk', 'Chair']

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

use Illuminate\Support\Arr;
 
$array = [
    ['name' => 'Desk'],
    ['name' => 'Table'],
    ['name' => 'Chair'],
];
 
$sorted = array_values(Arr::sortDesc($array, function (array $value) {
    return $value['name'];
}));
 
/*
    [
        ['name' => 'Table'],
        ['name' => 'Desk'],
        ['name' => 'Chair'],
    ]
*/

Arr::sortRecursive()

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::sortRecursiveDesc 方法:

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

Arr::toCssClasses()

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

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'
*/

Arr::toCssStyles()

Arr::toCssStyles 方法有条件地编译 CSS 样式字符串。该方法接受一个包含要添加的类或类的数组,其中数组键包含类,而值是一个布尔表达式。如果数组元素具有数字键,则它将始终包含在呈现的类列表中。

$hasColor = true;
 
$array = ['background-color: blue', 'color: blue' => $hasColor];
 
$classes = Arr::toCssStyles($array);
 
/*
    'background-color: blue; color: blue;'
*/

该方法用于强化 Laravel 的功能,可以将类与 Blade 组件的属性包进行合并,以及 @class Blade指令。

Arr::undot()

Arr::undot 方法将使用“.”表示法的单维数组展开为多维数组:

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 方法使用给定闭包对数组进行过滤:

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值:

use Illuminate\Support\Arr;
 
$array = [0, null];
 
$filtered = Arr::whereNotNull($array);
 
// [0 => 0]

Arr::wrap()

Arr::wrap 方法将给定值包裹到数组中,如果给定值已经是数组则保持不变:

use Illuminate\Support\Arr;

$string = 'Laravel';

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

// ['Laravel']

如果给定值是空的,则返回一个空数组:

use Illuminate\Support\Arr;

$nothing = null;

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

// []

data_fill()

data_fill 函数使用「.」号以嵌套数组或对象的方式设置缺失值:

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

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

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

data_fill($data, 'products.desk.discount', 10);

// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]

该函数还接收「*」号作为通配符并填充相应目标:

$data = [
    'products' => [
        ['name' => 'Desk 1', 'price' => 100],
        ['name' => 'Desk 2'],
    ],
];

data_fill($data, 'products.*.price', 200);

/*
    [
        'products' => [
            ['name' => 'Desk 1', 'price' => 100],
            ['name' => 'Desk 2', 'price' => 200],
        ],
    ]
*/

data_get()

data_get 函数使用「.」号从嵌套数组或对象中获取值:

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

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

// 100

data_get 函数还接收默认值,以便指定键不存在的情况下返回:

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

// 0

该函数还可以接收通配符 *,用于指向数组或对象的任意键:

$data = [
    '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 函数使用「.」号设置嵌套数组或对象的值:

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

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

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

该函数还接收通配符然后设置相应的目标值:

$data = [
    'products' => [
        ['name' => 'Desk 1', 'price' => 100],
        ['name' => 'Desk 2', 'price' => 150],
    ],
];

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

/*
    [
        'products' => [
            ['name' => 'Desk 1', 'price' => 200],
            ['name' => 'Desk 2', 'price' => 200],
        ],
    ]
*/

默认情况下,任意已存在的值都会被覆盖,如果你想要只设置不存在的值,可以传递 false 作为第三个参数:

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

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

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

data_forget()

data_forget 函数使用“.”符号来删除嵌套数组或对象中的值:

$data = ['products' => ['desk' => ['price' => 100]]];
 
data_forget($data, 'products.desk.price');
 
// ['products' => ['desk' => []]]

该函数还可以使用星号作为通配符,相应地删除目标上的值:

$data = [
    'products' => [
        ['name' => 'Desk 1', 'price' => 100],
        ['name' => 'Desk 2', 'price' => 150],
    ],
];
 
data_forget($data, 'products.*.price');
 
/*
    [
        'products' => [
            ['name' => 'Desk 1'],
            ['name' => 'Desk 2'],
        ],
    ]
*/

head()

head 函数只是简单返回给定数组的第一个元素:

$array = [100, 200, 300];

$first = head($array);

// 100

last()

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

$array = [100, 200, 300];

$last = last($array);

// 300

路径函数

app_path()

app_path 函数返回 app 目录的绝对路径,你还可以使用 app_path 函数为相对于 app 目录的给定文件生成绝对路径:

$path = app_path();

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

base_path()

base_path 函数返回项目根目录的绝对路径,你还可以使用 base_path 函数为相对于应用根目录的给定文件生成绝对路径:

$path = base_path();

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

config_path()

config_path 函数返回应用配置目录 config 的绝对路径,还可以使用 config_path 函数在应用配置目录内为给定文件生成完整路径:

$path = config_path();

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

database_path()

database_path 函数返回应用数据库目录 database 的完整路径,还可以使用 database_path 函数在数据库目录内为给定文件生成完整路径:

$path = database_path();

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

lang_path()

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

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

默认情况下,Laravel 应用程序框架不包括 lang 目录。如果您想自定义 Laravel 的语言文件,可以通过lang:publish Artisan命令发布它们。

mix()

mix 函数返回带有版本号的Mix文件路径:

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

public_path()

public_path 函数返回 public 目录的绝对路径,还可以使用 public_path 函数在 public 目录下为给定文件生成完整路径:

$path = public_path();

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

resource_path()

resource_path 函数返回 resources 目录的绝对路径,还可以使用 resources 函数在 resources 目录下为给定文件生成完整路径:

$path = resource_path();

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

storage_path()

storage_path 函数返回 storage 目录的绝对路径, 还可以使用 storage_path 函数在 storage 目录下为给定文件生成完整路径:

$path = storage_path();

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

字符串函数

__()

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

echo __('Welcome to our application');

echo __('messages.welcome');

如果给定翻译字符串或键不存在,__ 函数将会返回给定值。所以,使用上面的例子,如果翻译键不存在的话 __ 函数将会返回 messages.welcome

class_basename()

class_basename 返回给定类移除命名空间后的类名:

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

// Baz

e()

e 函数在给定字符串上运行 htmlentitiesdouble_encode 选项设置为 false):

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

// <html>foo</html>

preg_replace_array()

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

$string = 'The event will take place between :start and :end';

$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);

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

Str::after() Str::after 方法返回字符串中给定值之后的所有内容:

use Illuminate\Support\Str;

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

// ' my name'

Str::afterLast()

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

use Illuminate\Support\Str;

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

// 'Controller'

Str::ascii()

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

use Illuminate\Support\Str;

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

// 'u'

Str::before()

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

use Illuminate\Support\Str;

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

// 'This is '

Str::beforeLast()

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

use Illuminate\Support\Str;

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

// 'This '

Str::between()

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

use Illuminate\Support\Str;

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

// ' is my '

Str::betweenFirst()

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

use Illuminate\Support\Str;
 
$slice = Str::betweenFirst('[a] bc [d]', '[', ']');
 
// 'a'

Str::camel()

Str::camel 将给定字符串转化为形如 camelCase 的驼峰风格:

use Illuminate\Support\Str;

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

// fooBar

Str::contains()

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

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

use Illuminate\Support\Str;

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

// true

Str::endsWith()

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

Str::excerpt 方法从给定的字符串中提取一个片段,该片段与字符串中第一次出现的短语相匹配:

use Illuminate\Support\Str;
 
$excerpt = Str::excerpt('This is my name', 'my', [
    'radius' => 3
]);
 
// '...is my na...'

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

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

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

Str::finish()

Str::finish 方法添加给定值单个实例到字符串结尾 —— 如果原字符串不以给定值结尾的话:

use Illuminate\Support\Str;

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

// this/string/

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

// this/string/

Str::headline()

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

use Illuminate\Support\Str;
 
$headline = Str::headline('steve_jobs');
 
// Steve Jobs
 
$headline = Str::headline('EmailNotificationSent');
 
// Email Notification Sent

Str::inlineMarkdown()

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

use Illuminate\Support\Str;
 
$html = Str::inlineMarkdown('**Laravel**');
 
// <strong>Laravel</strong>

Str::is()

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

use Illuminate\Support\Str;

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

// true

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

// false

Str::isAscii()

Str::isAscii 方法会判断给定字符串是否是 7 位 ASCII:

use Illuminate\Support\Str;

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

// true

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

// false

Str::isJson()

Str::isJson 方法用来判断给定的字符串是否为有效的 JSON:

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::isUrl()

Str::isUrl 方法用来判断给定的字符串是否为有效的 URL:

use Illuminate\Support\Str;
 
$isUrl = Str::isUrl('http://example.com');
 
// 返回 true
 
$isUrl = Str::isUrl('laravel');
 
// 返回 false

Str::isUlid()

Str::isUlid 方法用来判断给定的字符串是否为有效的 ULID:

use Illuminate\Support\Str;
 
$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');
 
// 返回 true
 
$isUlid = Str::isUlid('laravel');
 
// 返回 false

Str::isUuid()

Str::isUuid()方法会判断给定字符串是否是有效的 UUID:

use Illuminate\Support\Str;

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

// true

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

// false

Str::kebab()

Str::kebeb 方法将给定字符串转化为形如 kebab-case 风格的字符串:

use Illuminate\Support\Str;

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

// foo-bar

Str::lcfirst()

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

use Illuminate\Support\Str;
 
$string = Str::lcfirst('Foo Bar');

// 结果为:foo Bar

Str::length()

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

use Illuminate\Support\Str;

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

// 7

Str::limit()

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

Str::lower() 方法会将给定字符串转化为小写格式:

use Illuminate\Support\Str;

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

// laravel

Str::markdown()

Str::markdown 方法将使用 CommonMark 将 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::mask()

Str::mask 方法用重复字符将字符串的一部分模糊,可以用来模糊邮件地址和电话号码等字符串片段。

use Illuminate\Support\Str;
 
$string = Str::mask('taylor@example.com', '*', 3);
 
// tay***************

如果需要,你可以为 mask 方法提供一个负数作为第三个参数,该方法将从字符串末尾指定距离处开始进行模糊处理:

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

Str::orderedUuid()

Str::orderedUuid 方法会生成一个「时间戳优先」 的 UUID 以便更高效地存储到数据库索引字段:

use Illuminate\Support\Str;

return (string) Str::orderedUuid();    

Str::padBoth()

Str::padBoth() 方法是对 PHP 函数 str_pad 的封装,会在字符串两边通过给定字符填充字符串到指定长度:

use Illuminate\Support\Str;

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

// '__James___'

// 默认通过空格填充到指定长度
$padded = Str::padBoth('James', 10);

// '  James   '

Str::padLeft()

Str::padLeft() 方法是对 PHP 函数 str_pad 的封装,会在字符串左侧通过给定字符填充字符串到指定长度:

use Illuminate\Support\Str;

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

// '-=-=-James'

// 默认通过空格填充到指定长度
$padded = Str::padLeft('James', 10);

// '     James'

Str::padRight()

Str::padRight() 方法是对 PHP 函数 str_pad 的封装,会在字符串右侧通过给定字符填充字符串到指定长度:

use Illuminate\Support\Str;

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

// 'James-----'

// 默认通过空格填充到指定长度
$padded = Str::padRight('James', 10);

// 'James     '

Str::password()

Str :: password 方法可用于生成给定长度的安全随机密码。密码将由字母、数字、符号和空格的组合构成。默认情况下,密码长度为32个字符:

use Illuminate\Support\Str;
 
$password = Str::password();
 
// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4'
 
$password = Str::password(12);
 
// 'qwuar>#V|i]N'

Str::plural()

Str::plural 方法将字符串转化为复数形式,这个函数支持 Laravel 的复数器所支持的任何语言

use Illuminate\Support\Str;

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

// cars

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

// children

还可以传递整型数据作为第二个参数到该函数以获取字符串的单数或复数形式:

use Illuminate\Support\Str;

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

// children

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

// child

Str::pluralStudly()

Str::pluralStudly 方法能将单数形式、骆驼形式的字符串转换为其复数形式。该函数支持 Laravel 的复数器所支持的所有语言:

use Illuminate\Support\Str;
 
$plural = Str::pluralStudly('VerifiedHuman');
 
// VerifiedHumans
 
$plural = Str::pluralStudly('UserFeedback');
 
// UserFeedbacks

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

use Illuminate\Support\Str;
 
$plural = Str::pluralStudly('VerifiedHuman', 2);
 
// VerifiedHumans
 
$singular = Str::pluralStudly('VerifiedHuman', 1);
 
// VerifiedHuman

Str::random()

Str::random 方法通过指定长度生成随机字符串,该函数使用了PHP的 random_bytes 函数:

use Illuminate\Support\Str;

$random = Str::random(40);

Str::remove()

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

使用 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::repeat()

Str::repeat 方法会重复给定的字符串:

use Illuminate\Support\Str;
 
$string = 'a';
 
$repeat = Str::repeat($string, 5);
 
// aaaaa

Str::replace()

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

use Illuminate\Support\Str;
 
$string = 'Laravel 8.x';
 
$replaced = Str::replace('8.x', '9.x', $string);
 
// Laravel 9.x

replace 方法还接受一个 caseSensitive 参数。默认情况下,replace 方法是区分大小写的:

Str::replace('Framework', 'Laravel', caseSensitive: false);

Str::replaceArray()

Str::replaceArray 方法使用数组在字符串序列中替换给定值:

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 方法会替换字符串中第一次出现的值:

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

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 方法用于反转给定的字符串:

use Illuminate\Support\Str;
 
$reversed = Str::reverse('Hello World');
 
// dlroW olleH

Str::singular()

Str::singular 方法将字符串转化为单数形式,这个函数支持 Laravel 的复数器所支持的任何语言

use Illuminate\Support\Str;

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

// car

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

// child

Str::slug()

Str::slug 方法将给定字符串生成 URL 友好的格式:

use Illuminate\Support\Str;

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

// laravel-5-framework

Str::snake()

Str::snake 方法将给定字符串转换为形如 snake_case 格式字符串:

use Illuminate\Support\Str;

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

// foo_bar

Str::squish()

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

use Illuminate\Support\Str;
 
$string = Str::squish('    laravel    framework    ');
 
// laravel framework

Str::start()

如果字符串没有以给定值开头的话 Str::start 方法会将给定值添加到字符串最前面:

use Illuminate\Support\Str;

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

// /this/string

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

// /this/string

Str::startsWith()

Str::startsWith 方法用于判断传入字符串是否以给定值开头:

use Illuminate\Support\Str;

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

// true

如果传入一个可能值的数组,startsWith 方法将在字符串以给定值之一开头时返回 true

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

Str::studly()

Str::studly 方法将给定字符串转化为形如 StudlyCase 的、单词开头字母大写的格式:

use Illuminate\Support\Str;

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

// FooBar

Str::substr()

Str::substr 方法会通过指定的起始位置和长度参数返回部分字符串:

use Illuminate\Support\Str;

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

// Laravel

Str::substrCount()

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

use Illuminate\Support\Str;
 
$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');
 
// 2

Str::substrReplace()

Str::substrReplace 方法在字符串的一部分中替换文本,从第三个参数指定的位置开始,用第四个参数指定的字符数进行替换。将0传递给方法的第四个参数将在指定位置插入字符串,而不替换字符串中的任何现有字符:

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

Str::swap()

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

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

Str::title()

Str::title 方法将字符串转化为形如 Title Case 的格式:

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 模板中显示:

use Illuminate\Support\Str;
 
$htmlString = Str::of('Nuno Maduro')->toHtmlString();

Str::ucfirst()

Str::ucfirst() 方法会以首字母大写格式返回给定字符串:

use Illuminate\Support\Str;

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

// Foo bar

Str::ucsplit()

Str::ucsplit 方法将给定的字符串按大写字母拆分为数组:

use Illuminate\Support\Str;
 
$segments = Str::ucsplit('FooBar');
 
// [0 => 'Foo', 1 => 'Bar']

Str::upper()

Str::upper 方法会将给定字符串转化为大写格式:

use Illuminate\Support\Str;

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

// LARAVEL

Str::ulid()

Str::ulid 方法生成一个 ULID,它是一个紧凑的、按时间排序的唯一标识符:

use Illuminate\Support\Str;
 
return (string) Str::ulid();
 
// 01gd6r360bp37zj17nxb55yv40

如果您想获取一个表示给定 ULID 创建日期和时间的 Illuminate\Support\Carbon 日期实例,您可以使用 Laravel 的 Carbon 集成提供的 createFromId 方法:

use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
 
$date = Carbon::createFromId((string) Str::ulid());

Str::uuid()

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

use Illuminate\Support\Str;

return (string) Str::uuid();

Str::wordCount()

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

use Illuminate\Support\Str;
 
Str::wordCount('Hello, world!'); // 2

Str::wordWrap()

Str::wordWrap 方法将字符串按照给定的字符数进行换行:

use Illuminate\Support\Str;
 
$text = "The quick brown fox jumped over the lazy dog."
 
Str::wordWrap($text, characters: 20, break: "<br />\n");
 
/*
The quick brown fox<br />
jumped over the lazy<br />
dog.
*/

Str::words()

Str::words() 方法会限制字符串单词个数:

use Illuminate\Support\Str;

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

// Perfectly balanced, as >>>

Str::wrap()

Str::wrap 方法用额外的字符串或字符串对包裹给定的字符串:

use Illuminate\Support\Str;
 
Str::wrap('Laravel', '"');
 
// "Laravel"
 
Str::wrap('is', before: 'This ', after: ' Laravel!');
 
// This is Laravel!

str()

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

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

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

$snake = str()->snake('FooBar');
 
// 'foo_bar'

trans()

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

echo trans('messages.welcome');

如果指定翻译键不存在,trans 函数会返回给定键,所以,以上面的示例为例,如果翻译键不存在,trans 函数会返回 messages.welcome

trans_choice()

trans_choice 函数翻译带拐点的给定翻译键:

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

如果指定的翻译键不存在,trans_choice 函数会将其返回。所以,以上面的示例为例,如果指定翻译键不存在 trans_choice 函数会返回 messages.notifications

流式字符串函数

流式字符串函数为处理字符串值提供了更加平滑的、面向对象的接口,通过这些函数,你可以将多个字符串操作以方法链的形式进行流式处理,这种方式比传统的字符串处理从语法角度来看可读性更好。

after

after方法返回字符串中给定值之后的所有字符,如果传入值在字符串中不存在的话则返回整个字符串:

use Illuminate\Support\Str;

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

// ' my name'

afterLast

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

use Illuminate\Support\Str;

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

// 'Controller'

append

append 方法用于追加给定值到字符串:

use Illuminate\Support\Str;

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

// 'Taylor Otwell'

ascii

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

use Illuminate\Support\Str;

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

// 'u'

basename

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

before 方法会返回字符串中给定值位置之前的所有字符:

use Illuminate\Support\Str;

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

// 'This is '

beforeLast

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

use Illuminate\Support\Str;

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

// 'This '

between

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

use Illuminate\Support\Str;
 
$converted = Str::of('This is my name')->between('This', 'name');
 
// ' is my '

betweenFirst

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

use Illuminate\Support\Str;
 
$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');
 
// 'a'

camel

camel 方法将给定字符串转化为形如 camelCase 的驼峰风格:

use Illuminate\Support\Str;

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

// fooBar

classBasename

classBasename 方法返回给定类的类名,去掉类的命名空间:

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

contains

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

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

use Illuminate\Support\Str;

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

// true

dirname

diranme 方法会返回给定字符串的父级部分(一般用于路径或目录字符串):

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'

excerpt

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

use Illuminate\Support\Str;
 
$excerpt = Str::of('This is my name')->excerpt('my', [
    'radius' => 3
]);
 
// '...is my na...'

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

此外,您可以使用省略选项来更改将添加到截断字符串前后的字符串:

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

endsWith

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

exactly 方法会判断指定字符串是否和另一个字符串匹配:

use Illuminate\Support\Str;

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

// true

explode

explode 方法会通过给定分割符对字符串进行切分,返回一个包含字符串分割后各个部分的集合:

use Illuminate\Support\Str;

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

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

finish

finish 方法添加给定值的单例到字符串结尾 —— 如果原字符串不以给定值结尾的话:

use Illuminate\Support\Str;

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

// this/string/

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

// this/string/

headline

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

use Illuminate\Support\Str;
 
$headline = Str::of('taylor_otwell')->headline();
 
// Taylor Otwell
 
$headline = Str::of('EmailNotificationSent')->headline();
 
// Email Notification Sent

inlineMarkdown

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

use Illuminate\Support\Str;
 
$html = Str::of('**Laravel**')->inlineMarkdown();
 
// <strong>Laravel</strong>

is

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

use Illuminate\Support\Str;

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

// true

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

// false

isAscii

isAscii 方法会判断给定字符串是否是 ASCII 字符串:

use Illuminate\Support\Str;

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

// true

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

// false

isEmpty

isEmpty 方法会判断给定字符串是否为空:

use Illuminate\Support\Str;

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

// true

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

// false

isNotEmpty

isNotEmpty 方法会判断给定字符串是否不为空:

use Illuminate\Support\Str;

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

// false

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

// true

isJson

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

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:

use Illuminate\Support\Str;
 
$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();
 
// true
 
$result = Str::of('Taylor')->isUlid();
 
// false

isUrl

isUrl 方法用于确定给定的字符串是否为 URL:

use Illuminate\Support\Str;
 
$result = Str::of('http://example.com')->isUrl();
 
// true
 
$result = Str::of('Taylor')->isUrl();
 
// false

isUuid

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

use Illuminate\Support\Str;
 
$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();
 
// true
 
$result = Str::of('Taylor')->isUuid();
 
// false

kebab

kebeb 方法将给定字符串转化为形如 kebab-case 风格(短划线连接)的字符串:

use Illuminate\Support\Str;

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

// foo-bar

lcfirst

lcfirst 方法将给定的字符串的第一个字符转换为小写:

use Illuminate\Support\Str;
 
$string = Str::of('Foo Bar')->lcfirst();
 
// foo Bar

length

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

use Illuminate\Support\Str;

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

// 7

limit

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

lower 方法将给定字符串转化为小写格式:

use Illuminate\Support\Str;

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

// 'laravel'

ltrim

ltrim 方法会清理给定字符串左侧字符(默认是空格):

use Illuminate\Support\Str;

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

// 'Laravel  '

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

// 'Laravel/'

markdown

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>

mask

mask 方法使用重复字符掩盖字符串的一部分,可用于混淆电子邮件地址和电话号码等字符串片段:

use Illuminate\Support\Str;
 
$string = Str::of('taylor@example.com')->mask('*', 3);
 
// tay***************

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

$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 方法将返回与给定正则表达式模式匹配的子字符串:

use Illuminate\Support\Str;

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

// 'bar'

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

// 'bar'

matchAll 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')->match('/f(\w*)/');

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

如果没有匹配到任何结果,将返回一个空集合。

isMatch

isMatch 方法将返回 true,如果字符串与给定的正则表达式匹配:

use Illuminate\Support\Str;
 
$result = Str::of('foo bar')->isMatch('/foo (.*)/');
 
// true
 
$result = Str::of('laravel')->isMatch('/foo (.*)/');
 
// false

newLine

newLine 方法向字符串附加一个“换行符”字符:

use Illuminate\Support\Str;
 
$padded = Str::of('Laravel')->newLine()->append('Framework');
 
// 'Laravel
//  Framework'

padBoth()

padBoth 方法是对 PHP 函数 str_pad 的封装,会在字符串两边通过给定字符填充字符串到指定长度:

use Illuminate\Support\Str;

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

// '__James___'

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

// '  James   '

padLeft

padLeft 方法是对 PHP 函数 str_pad 的封装,会在字符串左侧通过给定字符填充字符串到指定长度:

use Illuminate\Support\Str;

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

// '-=-=-James'

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

// '     James'

padRight

padRight 方法是对 PHP 函数 str_pad 的封装,会在字符串右侧通过给定字符填充字符串到指定长度:

use Illuminate\Support\Str;

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

// 'James-----'

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

// 'James     '

pipe

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');
 
// 'Checksum: a5c95b86291ea299fcbe64458ed12702'
 
$closure = Str::of('foo')->pipe(function (Stringable $str) {
    return 'bar';
});
 
// 'bar'

plural

plural 方法会将单个单词字符串转化为复数格式,该函数支持 Laravel 复数器支持的所有语言:

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

prepend 方法可以在字符串前面添加值:

use Illuminate\Support\Str;

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

// Laravel Framework

remove

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

use Illuminate\Support\Str;
 
$string = Str::of('Arkansas is quite beautiful!')->remove('quite');
 
// Arkansas is beautiful!

您也可以将 false 作为第二个参数传递,以忽略大小写。

repeat

repeat 方法重复给定的字符串:

use Illuminate\Support\Str;
 
$repeated = Str::of('a')->repeat(5);
 
// aaaaa

replace

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

use Illuminate\Support\Str;

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

// Laravel 7.x

replace 方法还接受一个 caseSensitive 参数。默认情况下,replace 方法是区分大小写的:

$replaced = Str::of('macOS 13.x')->replace(
    'macOS', 'iOS', caseSensitive: false
);

replaceArray

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

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 方法会在字符串中给定值第一次出现的位置进行替换:

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

rtrim 会清理给定字符串右侧的字符(默认是空格):

use Illuminate\Support\Str;

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

// '  Laravel'

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

// '/Laravel'

scan

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

use Illuminate\Support\Str;
 
$collection = Str::of('filename.jpg')->scan('%[^.].%s');
 
// collect(['filename', 'jpg'])

singular

singular 方法将字符串转化为单数形式,该函数支持 Laravel 复数器支持的所有语言:

use Illuminate\Support\Str;

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

// car

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

// child

slug

slug 方法将给定字符串生成 URL 友好的格式:

use Illuminate\Support\Str;

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

// laravel-framework

snake

snake 方法将给定字符串转换为形如 snake_case 格式(下划线连接风格)字符串:

use Illuminate\Support\Str;

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

// foo_bar

split

split 方法会通过正则表达式将给定字符串切分成子字符串集合:

use Illuminate\Support\Str;

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

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

squish

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

use Illuminate\Support\Str;
 
$string = Str::of('    laravel    framework    ')->squish();
 
// laravel framework

start

start 方法会在字符串不是以给定值开头的情况下,添加给定值到字符串:

use Illuminate\Support\Str;

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

// /this/string

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

// /this/string

startsWith

startsWith 方法用于判断传入字符串是否以给定值开头:

use Illuminate\Support\Str;

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

// true

studly

studly 方法将给定字符串转化为形如 StudlyCase 的、单词开头字母大写的格式:

use Illuminate\Support\Str;

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

// FooBar

substr

substr 方法通过指定开头字符和长度截取字符串并返回:

use Illuminate\Support\Str;

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

// Framework

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

// Frame

substrReplace

substrReplace 方法替换字符串的一部分,从第二个参数指定的位置开始替换由第三个参数指定的字符数。将 0 传递给方法的第三个参数将在指定位置插入字符串,而不替换字符串中的任何现有字符:

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 函数替换字符串中的多个值:

use Illuminate\Support\Str;

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

// Burritos are fantastic!

tap

tap 方法将字符串传递给给定的闭包,允许您检查和与字符串交互,同时不影响字符串本身。tap 方法始终返回原始字符串,无论闭包返回什么:

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

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

// LARAVEL FRAMEWORK

test

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

use Illuminate\Support\Str;

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

// true

title

title 方法会将给定字符串转化为形如 Title 的这种风格:

use Illuminate\Support\Str;

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

// A Nice Title Uses The Correct Case

trim

trim 方法会清除给定字符串前后的空格:

use Illuminate\Support\Str;

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

// 'Laravel'

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

// 'Laravel'

ucfirst()

ucfirst 方法会以首字母大写格式返回给定字符串:

use Illuminate\Support\Str;

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

// Foo bar

ucsplit

ucsplit 方法将给定字符串按大写字母拆分成一个集合:

use Illuminate\Support\Str;
 
$string = Str::of('Foo Bar')->ucsplit();
 
// collect(['Foo', 'Bar'])

upper

upper 方法会将给定字符串转化为大写格式:

use Illuminate\Support\Str;

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

// LARAVEL

when

when 方法会在给定条件为 true 时调用给定闭包,该闭包接收流式字符串实例作为参数:

use Illuminate\Support\Str;

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

// 'Taylor Otwell'

如果必要的话,你可以传递另一个闭包作为 when 方法的第三个参数,这个闭包会在条件参数为 false 时执行。

whenContains

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('tony stark')
            ->whenContains('tony', function (Stringable $string) {
                return $string->title();
            });
 
// 'Tony Stark'

必要时,您可以将另一个闭包作为 when 方法的第三个参数传递。这个闭包将在字符串不包含给定值时执行。

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('tony stark')
            ->whenContains(['tony', 'hulk'], function (Stringable $string) {
                return $string->title();
            });
 
// Tony Stark

whenContainsAll

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('tony stark')
                ->whenContainsAll(['tony', 'stark'], function (Stringable $string) {
                    return $string->title();
                });
 
// 'Tony Stark'

必要时,您可以将另一个闭包作为 when 方法的第三个参数传递。这个闭包将在条件参数求值为 false 时执行。

whenEmpty

whenEmpty 方法会在字符串为空时调用给定闭包,如果闭包有返回值,则该返回值被 whenEmpty 方法返回,否则,字符串实例本身会被返回:

use Illuminate\Support\Str;

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

// 'Laravel'

whenNotEmpty

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('Framework')->whenNotEmpty(function (Stringable $string) {
    return $string->prepend('Laravel ');
});
 
// 'Laravel Framework'

whenStartsWith

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('disney world')->whenStartsWith('disney', function (Stringable $string) {
    return $string->title();
});
 
// 'Disney World'

whenEndsWith

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('disney world')->whenEndsWith('world', function (Stringable $string) {
    return $string->title();
});
 
// 'Disney World'

whenExactly

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('laravel')->whenExactly('laravel', function (Stringable $string) {
    return $string->title();
});
 
// 'Laravel'

whenNotExactly

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('framework')->whenNotExactly('laravel', function (Stringable $string) {
    return $string->title();
});
 
// 'Framework'

whenIs

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

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

whenIsAscii

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {
    return $string->title();
});
 
// 'Laravel'

whenIsUlid

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

use Illuminate\Support\Str;
 
$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function (Stringable $string) {
    return $string->substr(0, 8);
});
 
// '01gd6r36'

whenIsUuid

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

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

whenTest

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('laravel framework')->whenTest('/laravel/', function (Stringable $string) {
    return $string->title();
});
 
// 'Laravel Framework'

wordCount

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

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

words

words 方法会限制字符串单词个数:

use Illuminate\Support\Str;

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

// Perfectly balanced, as >>>

URL 函数

action()

action 函数为给定控制器动作生成 URL,你不需要传递完整的命名空间到该控制器,传递相对于命名空间 App\Http\Controllers 的类名即可:

$url = action('HomeController@index');

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

如果该方法接收路由参数,你可以将其作为第二个参数传递进来:

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

asset()

asset 函数使用当前请求的 scheme(HTTP 或 HTTPS)为前端资源生成一个 URL:

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

你可以通过在 .env 文件中设置 ASSET_URL 变量来配置资源 URL 主机名,如果你将资源托管在第三方服务如 Amazon S3 时,这一功能很有用:

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

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

route()

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

$url = route('routeName');

如果该路由接收参数,你可以将其作为第二个参数传递进来:

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

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

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

secure_asset()

secure_asset 函数使用 HTTPS 为前端资源生成一个 URL:

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

secure_url()

secure_url 函数为给定路径生成完整的 HTTPS URL:

echo secure_url('user/profile');

echo secure_url('user/profile', [1]);

to_route()

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

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

如果需要,你可以将应分配给重定向的 HTTP 状态码以及任何额外的响应头作为第三个和第四个参数传递给to_route 函数:

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

url()

url 函数为给定路径生成完整URL:

echo url('user/profile');

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

如果没有提供路径,将会返回 Illuminate\Routing\UrlGenerator 实例:

echo url()->current();
echo url()->full();
echo url()->previous();

其它函数

abort()

abort 函数会抛出一个被异常处理器渲染的 HTTP 异常

abort(403);

还可以提供异常响应文本以及自定义响应头:

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

abort_if()

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

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

abort 一样,你还可以传递异常响应文本作为第三个参数以及自定义响应头数组作为第四个参数。

abort_unless()

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

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

abort 一样,你还可以传递异常响应文本作为第三个参数以及自定义响应头数组作为第四个参数。

app()

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

$container = app();

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

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

auth()

auth 函数返回一个认证器实例,为方便起见你可以用其取代 Auth 门面:

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

如果需要的话还可以指定你想要使用的 guard 实例:

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

back()

back 函数生成HTTP 重定向响应到用户前一个访问页面:

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

return back();

bcrypt()

bcrypt 函数使用 Bcrypt 对给定值进行哈希,你可以用其替代 Hash 门面:

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

blank()

blank 函数返回给定值是否为空:

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

// true

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

// false

blank 相对的是 filled 函数。

broadcast()

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

broadcast(new UserRegistered($user));

cache()

cache 函数可以用于从缓存中获取值,如果给定 key 在缓存中不存在,可选的默认值会被返回:

$value = cache('key');

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

你可以通过传递数组键值对到函数来添加数据项到缓存。还需要传递缓存有效期(秒数):

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

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

class_uses_recursive()

class_uses_recursive 函数某个类所使用的所有 trait,包括子类使用的:

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

collect()

collect 函数会根据提供的数据项创建一个集合

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

config()

config 函数获取配置变量的值,配置值可以通过使用”.”号访问,包含文件名以及你想要访问的选项。如果配置选项不存在的话默认值将会被指定并返回:

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

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

辅助函数 config 还可以用于在运行时通过传递键值对数组设置配置变量值:

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

cookie()

cookie 函数可用于创建一个新的 Cookie 实例:

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

csrf_field()

csrf_field 函数生成一个包含 CSRF 令牌值的 HTML 隐藏字段,例如,使用Blade语法示例如下:

{{ csrf_field() }}

csrf_token()

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

$token = csrf_token();

dd()

dd 函数输出给定变量值并终止脚本执行:

dd($value);

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

如果你不想停止脚本的运行,可以使用 dump 函数。

decrypt()

decrypt 函数使用 Laravel 加密器对给定值进行解密:

$decrypted = decrypt($encrypted_value);

dispatch()

dispatch 函数推送一个新的任务到 Laravel 任务队列

dispatch(new App\Jobs\SendEmails);

dispatch_sync()

dispatch_sync 函数会立即运行给定任务并返回 handle 方法处理结果:

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

dump()

dump 函数会打印给定变量:

dump($value);

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

如果你想要在打印变量后终止脚本执行,可以使用 dd 函数替代之。

注:你可以使用 Artisan 的 dump-server 命令拦截所有 dump 调用并在控制台窗口显示它们。

encrypt()

encrypt 函数使用 Laravel 加密器加密给定字符串:

$encrypted = encrypt($unencrypted_value);

env()

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

$env = env('APP_ENV');

// 如果变量不存在返回默认值...
$env = env('APP_ENV', 'production');

如果你在开发过程中执行了 config:cache 命令,需要确保只在配置文件中调用了 env,一旦配置被缓存起来,.env 文件将不会被加载,因此所有对 env 函数的调用都会返回 null

event()

event 函数分发给定事件到对应监听器:

event(new UserRegistered($user));

fake()

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

@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() 函数来指定区域设置。每个区域设置都将解析为一个单独的单例:

fake('nl_NL')->name()

filled()

filled 函数会返回给定值是否不为空:

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

// true

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

// false

filled 相对的是 blank 函数。

info()

info 函数会记录信息到日志系统

info('Some helpful information!');

还可以传递上下文数据数组到该函数:

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

logger()

logger 函数可以用于记录 debug 级别的日志消息:

logger('Debug message');

同样,也可以传递上下文数据数组到该函数:

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

如果没有值传入该函数的话会返回日志实例:

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

method_field()

method_field 函数生成包含 HTTP 请求方法的 HTML hidden 表单字段,例如:

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

now()

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

$now = now();

old()

old 函数获取存放在一次性 Session 中上一次输入的值:

$value = old('value');

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

由于在 old 函数的第二个参数中提供的“默认值”通常是 Eloquent 模型的属性,Laravel 允许您只需将整个 Eloquent 模型作为old函数的第二个参数传递。这样做时,Laravel 会假设提供给old函数的第一个参数是应被视为“默认值”的 Eloquent 属性的名称:

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

// 等同于...

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

optional()

optional 函数接收任意参数并允许你访问对象上的属性或调用其方法。如果给定的对象为空,属性或方法调用返回 null 而不是出错:

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

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

optional 函数还可以接收一个闭包作为第二个参数,闭包会在第一个参数值不为空的情况下调用:

return optional(User::find($id), function ($user) {
    return new DummyUser;
});

policy()

policy 函数为给定模型类获取对应策略实例:

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

redirect()

redirect 函数返回 HTTP 重定向响应,如果不带参数的话返回重定向器示例:

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

return redirect('/home');

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

report()

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

report($e);

报告功能还可以接受字符串作为参数。当给定一个字符串时,该函数将创建一个异常,将给定的字符串作为其消息:

report('Something went wrong.');

report_if()

如果给定条件为真,则 report_if 函数将使用您的异常处理程序报告异常:

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

report_unless()

如果给定条件为假,则 report_unless 函数将使用您的异常处理程序报告异常:

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

request()

request 函数返回当前请求实例或者获取一个输入项:

$request = request();

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

rescue()

rescue 函数可以执行给定闭包并捕获执行过程中的所有异常。这些捕获的异常会发送给异常处理器report 方法,不过,请求会继续执行:

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

还可以传递第二个参数到 rescue 函数,作为在执行闭包出现异常的情况下返回的默认值:

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

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

可以将报告参数提供给"rescue"函数来决定是否通过"report"函数报告异常:

return rescue(function () {
    return $this->method();
}, report: function (Throwable $throwable) {
    return $throwable instanceof InvalidArgumentException;
});

resolve()

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

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

response()

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

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

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

retry()

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

return retry(5, function () {
    // Attempt 5 times while resting 100ms in between attempts...
}, 100);    

如果你想要手动计算重试之间的毫秒数,你可以将一个闭包作为 retry 函数的第三个参数传入:

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

为了方便起见,你可以将一个数组作为 retry 函数的第一个参数。该数组将用于确定在后续重试之间等待多少毫秒:

return retry([100, 200], function () {
    // Sleep for 100ms on first retry, 200ms on second retry...
});

如果只在特定条件下重试,则可以将一个闭包作为 retry 函数的第四个参数传入:

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

session()

session 函数可以用于获取/设置 Session 值:

$value = session('key');

可以通过传递键值对数组到该函数的方式设置 Session 值:

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

如果没有传入参数到 session 函数则返回 Session 存储器对象实例:

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

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

tap()

tap 函数接收两个参数:任意的 $value 和一个闭包。$value 会被传递到闭包然后通过 tap 函数返回。闭包返回值与函数返回值不相关:

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

    $user->save();
});

如果没有传入闭包到 tap 函数,那么你可以调用给定 $value 上面的任意方法,调用方法的返回值永远都是 $value,不管在方法中定义的返回值是什么。例如,Eloquent update 方法通常返回一个整型,不过,我们可以通过 tap 函数强制该方法返回模型本身:

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

要添加 tap 方法到一个类,可以在对应类中使用 Illuminate\Support\Traits\Tappable trait,该 trait 中包含的tap 方法接收一个闭包作为唯一参数,对象实例本身会被传递到该闭包,然后通过 tap 方法返回:

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

throw_if()

throw_if 函数会在给定布尔表达式为 true 的情况下抛出给定异常:

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 的情况下抛出给定异常:

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 实例:

$today = today();

trait_uses_recursive()

trait_uses_recursive 函数会返回某个 trait 使用的所有 trait:

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

transform()

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

validator 函数通过给定参数创建一个新的验证器实例,为方便起见可以使用它代替 Validator 门面:

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

value()

value 函数返回给定的值,不过,如果你传递一个闭包到该函数,该闭包将会被执行并返回执行结果:

$result = value(true);

// true

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

// false

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

$result = value(function (string $name) {
    return $name;
}, 'Taylor');
 
// 'Taylor'

view()

view 函数获取一个视图实例:

return view('auth.login');

with()

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

其他工具

基准测试

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

<?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 类将返回执行回调所需的平均毫秒数:

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

有时,您可能希望对回调的执行进行基准测试,同时仍然获取回调返回的值。value 方法将返回一个元组,其中包含回调返回的值和执行回调所需的毫秒数:

[$count, $duration] = Benchmark::value(fn () => User::count());

日期

Laravel 包含 Carbon,一个强大的日期和时间操作库。要创建一个新的 Carbon 实例,可以调用 now 函数。此函数在 Laravel 应用程序中全局可用:

$now = now();

或者,可以使用 Illuminate\Support\Carbon 类创建一个新的 Carbon 实例:

use Illuminate\Support\Carbon;
 
$now = Carbon::now();

有关 Carbon 及其功能的详细讨论,请参阅官方 Carbon 文档

抽奖

Laravel 的抽奖类可用于根据一组给定的概率执行回调。当您只想为一部分传入请求执行代码时,这将非常有用:

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

您可以将 Laravel 的抽奖类与其他 Laravel 功能结合使用。例如,您可能只希望将较小比例的慢查询报告给异常处理程序。由于抽奖类是可调用的,因此可以将类的实例传递给接受可调用对象的任何方法:

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 提供了一些简单的方法,让您可以轻松测试应用程序的抽奖调用:

// 抽奖总是获胜...
Lottery::alwaysWin();

// 抽奖总是失败...
Lottery::alwaysLose();

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

// 抽奖恢复正常行为...
Lottery::determineResultsNormally();

管道

Laravel 的管道门面提供了一种方便的方式,通过一系列可调用的类、闭包或可调用对象将给定的输入流入到管道中,使每个类有机会检查或修改输入并调用管道中的下一个可调用对象:

use Closure;
use App\Models\User;
use Illuminate\Support\Facades\Pipeline;
 
$user = Pipeline::send($user)
            ->through([
                function (User $user, Closure $next) {
                    // ...
 
                    return $next($user);
                },
                function (User $user, Closure $next) {
                    // ...
 
                    return $next($user);
                },
            ])
            ->then(fn (User $user) => $user);

如您所见,管道中的每个可调用类或闭包都会提供输入和 $next 闭包。调用 $next 闭包将调用管道中的下一个可调用对象。正如您可能已经注意到的那样,这与中间件非常相似。

当管道中的最后一个可调用对象调用 $next 闭包时,将调用传递给 then 方法的可调用对象。通常,这个可调用对象将简单地返回给定的输入。

当然,如前所述,您不仅限于为管道提供闭包。您还可以提供可调用类。如果提供了类名,则通过 Laravel 的服务容器实例化类,允许将依赖项注入到可调用类中:

$user = Pipeline::send($user)
            ->through([
                GenerateProfilePhoto::class,
                ActivateSubscription::class,
                SendWelcomeEmail::class,
            ])
            ->then(fn (User $user) => $user);

休眠

Laravel 的 Sleep 类是对 PHP 原生的 sleepusleep 函数的轻量级封装,提供了更好的可测试性,同时还为处理时间提供了开发者友好的 API:

use Illuminate\Support\Sleep;
 
$waiting = true;
 
while ($waiting) {
    Sleep::for(1)->second();
 
    $waiting = /* ... */;
}

Sleep 类提供了各种方法,可以让您使用不同的时间单位:

// 暂停90秒...
Sleep::for(1.5)->minutes();

// 暂停2秒...
Sleep::for(2)->seconds();

// 暂停500毫秒...
Sleep::for(500)->milliseconds();

// 暂停5,000微秒...
Sleep::for(5000)->microseconds();

// 直到给定的时间...
Sleep::until(now()->addMinute());

// PHP原生的"sleep"函数的别名...
Sleep::sleep(2);

// PHP原生的"usleep"函数的别名...
Sleep::usleep(5000);

为了方便地组合时间单位,您可以使用 and 方法:

Sleep::for(1)->second()->and(10)->milliseconds();

测试休眠

当测试使用 Sleep 类或 PHP 原生的 sleep 函数的代码时,测试将暂停执行。如您所料,这会使您的测试套件显着变慢。例如,想象一下您正在测试以下代码:

$waiting = /* ... */;
 
$seconds = 1;
 
while ($waiting) {
    Sleep::for($seconds++)->seconds();
 
    $waiting = /* ... */;
}

通常,测试这段代码至少需要一秒钟。幸运的是,Sleep 类允许我们"伪造"休眠,以使我们的测试套件保持快速:

public function test_it_waits_until_ready()
{
    Sleep::fake();
 
    // ...
}

当伪造 Sleep 类时,实际执行暂停将被跳过,从而大大加快了测试。

一旦伪造了 Sleep 类,就可以根据应有的"休眠"进行断言。为了说明这一点,让我们想象一下我们正在测试的代码暂停执行三次,每次暂停增加一秒钟。使用 assertSequence 方法,我们可以断言我们的代码在正确的时间内进行了"休眠",同时保持了测试的速度:

public function test_it_checks_if_ready_four_times()
{
    Sleep::fake();
 
    // ...
 
    Sleep::assertSequence([
        Sleep::for(1)->second(),
        Sleep::for(2)->seconds(),
        Sleep::for(3)->seconds(),
    ]);
}

当然,Sleep 类在测试时还提供了其他各种断言方法:

use Carbon\CarbonInterval as Duration;
use Illuminate\Support\Sleep;

// 断言调用了3次sleep...
Sleep::assertSleptTimes(3);

// 断言休眠持续时间...
Sleep::assertSlept(function(Duration $duration): bool {
    return /* ... */;
}, times: 1);

// 断言从未调用过Sleep类...
Sleep::assertNeverSlept();

// 断言即使调用了Sleep,也没有发生暂停...
Sleep::assertInsomniac();

有时,在应用程序代码中发生模拟休眠时,执行某个动作可能很有用。为此,您可以为 whenFakingSleep 方法提供一个回调。在下面的示例中,我们使用 Laravel 的时间操作助手来立即通过每个休眠的持续时间推进时间:

use Carbon\CarbonInterval as Duration;

$this->freezeTime();

Sleep::fake();

Sleep::whenFakingSleep(function(Duration $duration) {
    // 模拟休眠时推进时间...
    $this->travel($duration->totalMilliseconds)->milliseconds();
});

当暂停执行时,Laravel 内部会使用 Sleep 类。例如,retry 助手在休眠时使用 Sleep 类,从而在使用该助手时提高了可测试性。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: 文件存储

>> 下一篇: HTTP Client