辅助函数


简介

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

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

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

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

use Illuminate\Support\Str;

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

// this/string/

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

// this/string/

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

Str::plural 方法将字符串转化为复数形式,该函数当前只支持英文:

use Illuminate\Support\Str;

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

// cars

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

// children

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

use Illuminate\Support\Str;

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

// children

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

// child

Str::random()

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

use Illuminate\Support\Str;

$random = Str::random(40);

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

Str::singular 方法将字符串转化为单数形式,该函数目前只支持英文:

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

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

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

use Illuminate\Support\Str;

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

// Foo bar

Str::upper()

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

use Illuminate\Support\Str;

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

// LARAVEL

Str::uuid()

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

use Illuminate\Support\Str;

return (string) Str::uuid();

Str::words()

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

use Illuminate\Support\Str;

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

// Perfectly balanced, as >>>

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 '

camel

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

use Illuminate\Support\Str;

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

// fooBar

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'

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/

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

kebab

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

use Illuminate\Support\Str;

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

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

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

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

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     '

plural

plural 方法会将单个单词字符串转化为复数格式,该函数目前仅支持英语:

use Illuminate\Support\Str;

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

// cars

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

// children

你可以提供一个整型数字作为第二个参数传递到该函数来获取字符串的单数和复数格式:

use Illuminate\Support\Str;

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

// children

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

// child

prepend

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

use Illuminate\Support\Str;

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

// Laravel Framework

replace

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

use Illuminate\Support\Str;

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

// Laravel 7.x

replaceArray

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

use Illuminate\Support\Str;

$string = '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'

singular

singular 方法将字符串转化为单数形式,该函数目前只支持英文:

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"])

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

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

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 时执行。

whenEmpty

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

use Illuminate\Support\Str;

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

// 'Laravel'

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

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

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

$result = dispatch_now(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));

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

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

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

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

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

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

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

<< 上一篇: 文件存储

>> 下一篇: HTTP 客户端