Laravel 8 中文文档 辅助函数

enrique · 2021-05-09 18:16:09 · 热度: 208

简介

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

可用方法

数组 & 对象

Arr::accessible
Arr::add
Arr::collapse
Arr::crossJoin
Arr::divide
Arr::dot
Arr::except
Arr::exists
Arr::first
Arr::flatten
Arr::forget
Arr::get
Arr::has
Arr::hasAny
Arr::isAssoc
Arr::last
Arr::only
Arr::pluck
Arr::prepend
Arr::pull
Arr::query
Arr::random
Arr::set
Arr::shuffle
Arr::sort
Arr::sortRecursive
Arr::where
Arr::wrap
data_fill
data_get
data_set
head
last

路径

app_path
base_path
config_path
database_path
mix
public_path
resource_path
storage_path

字符串

__
class_basename
e
preg_replace_array
Str::after
Str::afterLast
Str::ascii
Str::before
Str::beforeLast
Str::between
Str::camel
Str::contains
Str::containsAll
Str::endsWith
Str::finish
Str::is
Str::isAscii
Str::isUuid
Str::kebab
Str::length
Str::limit
Str::lower
Str::orderedUuid
Str::padBoth
Str::padLeft
Str::padRight
Str::plural
Str::random
Str::replaceArray
Str::replaceFirst
Str::replaceLast
Str::singular
Str::slug
Str::snake
Str::start
Str::startsWith
Str::studly
Str::substr
Str::title
Str::ucfirst
Str::upper
Str::uuid
Str::words
trans
trans_choice

流畅的字符串

after
afterLast
append
ascii
basename
before
beforeLast
camel
contains
containsAll
dirname
endsWith
exactly
explode
finish
is
isAscii
isEmpty
isNotEmpty
kebab
length
limit
lower
ltrim
match
matchAll
padBoth
padLeft
padRight
plural
prepend
replace
replaceArray
replaceFirst
replaceLast
replaceMatches
rtrim
singular
slug
snake
split
start
startsWith
studly
substr
title
trim
ucfirst
upper
when
whenEmpty
words

URLs

action
asset
route
secure_asset
secure_url
url

其他

abort
abort_if
abort_unless
app
auth
back
bcrypt
blank
broadcast
cache
class_uses_recursive
collect
config
cookie
csrf_field
csrf_token
dd
dispatch
dispatch_now
dump
env
event
filled
info
logger
method_field
now
old
optional
policy
redirect
report
request
rescue
resolve
response
retry
session
tap
throw_if
throw_unless
today
trait_uses_recursive
transform
validator
value
view
with

方法列表

数组 & 对象

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

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

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

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

// true

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

// true

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

// false

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

// false

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

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

use Illuminate\Support\Arr;

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

// $keys: ['name']

// $values: ['Desk']

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

use Illuminate\Support\Arr;

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

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

// true

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

// false

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

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

use Illuminate\Support\Arr;

$array = [100, 200, 300];

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

// 200

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

use Illuminate\Support\Arr;

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

use Illuminate\Support\Arr;

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

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

// ['products' => []]

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

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

use Illuminate\Support\Arr;

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

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

// 100

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

use Illuminate\Support\Arr;

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

// 0

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

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

use Illuminate\Support\Arr;

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

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

// true

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

// false

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

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

use Illuminate\Support\Arr;

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

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

// true

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

// true

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

// false

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

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

use Illuminate\Support\Arr;

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

// true

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

// false

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

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

use Illuminate\Support\Arr;

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

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

// 300

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

use Illuminate\Support\Arr;

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

use Illuminate\Support\Arr;

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

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

// ['Taylor', 'Abigail']

你也可以指定结果的键:

use Illuminate\Support\Arr;

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

use Illuminate\Support\Arr;

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

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

// $name: Desk

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

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

use Illuminate\Support\Arr;

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

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

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

use Illuminate\Support\Arr;

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

Arr::query($array);

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

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

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

use Illuminate\Support\Arr;

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

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

// 4 - (retrieved randomly)

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

use Illuminate\Support\Arr;

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

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

use Illuminate\Support\Arr;

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

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

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

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

Arr::wrap 函数可以将给定值转换为一个数组。如果给定值已经是一个数组,将不会被转换:

use Illuminate\Support\Arr;

$string = 'Laravel';

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

// ['Laravel']

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

use Illuminate\Support\Arr;

$nothing = null;

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

// []

data_fill() {#collection-method}

data_fill 函数使用「.」符号给多维数组或对象设置缺省值:

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

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

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

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

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

这个函数也可以接收「*」 作为通配符,并设置相应缺省值:

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

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

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

data_get() {#collection-method}

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

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

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

// 100

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() {#collection-method}

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() {#collection-method}

head 函数将返回数组中的第一个值:

$array = [100, 200, 300];

$first = head($array);

// 100

last() {#collection-method}

last 函数将返回数组中的最后一个值:

$array = [100, 200, 300];

$last = last($array);

// 300

路径

app_path() {#collection-method}

app_path 函数返回 app 目录的完整路径。您亦可使用 app_path 函数来生成应用目录下特定文件的完整路径:

$path = app_path();

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

base_path() {#collection-method}

base_path 函数返回项目根目录的完整路径。您亦可使用 base_path 函数生成项目根目录下特定文件的完整路径:

$path = base_path();

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

config_path() {#collection-method}

config_path 函数返回 config 目录的完整路径。您亦可使用 config_path 函数来生成应用配置目录中的特定文件的完整路径:

$path = config_path();

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

database_path() {#collection-method}

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

$path = database_path();

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

mix() {#collection-method}

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

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

public_path() {#collection-method}

public_path 函数返回 public 目录的完整路径。您亦可使用 public_path 函数来生成 public 目录下特定文件的完整路径:

$path = public_path();

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

resource_path() {#collection-method}

resource_path 函数返回 resources 目录的完整路径。您亦可使用 resource_path 函数来生成位于资源路径中的特定文件的路径:

$path = resource_path();

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

storage_path() {#collection-method}

storage_path 函数返回 storage 目录的完整路径。您亦可使用 storage_path 函数来生成 storage 目录下特定文件的完整路径:

$path = storage_path();

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

字符串函数

__() {#collection-method}

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

echo __('Welcome to our application');

echo __('messages.welcome');

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

class_basename() {#collection-method}

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

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

// Baz

e() {#collection-method}

e 函数在指定字符串上运行 PHPhtmlspecialchars 函数( double_encode 选项为 true ):

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

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

preg_replace_array() {#collection-method}

preg_replace_array 函数使用正则表达式用给定的数组替换字符串中的内容后的结果:

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

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

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

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

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

use Illuminate\Support\Str;

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

// ' my name'

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

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

use Illuminate\Support\Str;

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

// 'Controller'

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

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

use Illuminate\Support\Str;

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

// 'u'

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

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

use Illuminate\Support\Str;

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

// 'This is '

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

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

use Illuminate\Support\Str;

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

// 'This '

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

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

use Illuminate\Support\Str;

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

// ' is my '

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

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

use Illuminate\Support\Str;

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

// fooBar

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

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

use Illuminate\Support\Str;

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

// true

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

use Illuminate\Support\Str;

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

// true

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

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

use Illuminate\Support\Str;

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

// true

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

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

use Illuminate\Support\Str;

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

// true

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

use Illuminate\Support\Str;

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

// true

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

// false

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

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

use Illuminate\Support\Str;

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

// this/string/

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

// this/string/

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

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

use Illuminate\Support\Str;

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

// true

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

// false

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

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

use Illuminate\Support\Str;

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

// true

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

// false

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

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

use Illuminate\Support\Str;

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

// true

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

// false

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

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

use Illuminate\Support\Str;

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

// foo-bar

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

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

use Illuminate\Support\Str;

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

// 7

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

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

use Illuminate\Support\Str;

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

// The quick brown fox...

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

use Illuminate\Support\Str;

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

// The quick brown fox (...)

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

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

use Illuminate\Support\Str;

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

// laravel

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

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

use Illuminate\Support\Str;

return (string) Str::orderedUuid();

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

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

use Illuminate\Support\Str;

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

// '__James___'

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

// '  James   '

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

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

use Illuminate\Support\Str;

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

// '-=-=-James'

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

// '     James'

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

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

use Illuminate\Support\Str;

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

// 'James-----'

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

// 'James     '

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

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

use Illuminate\Support\Str;

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

// cars

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

// children

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

use Illuminate\Support\Str;

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

// children

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

// child

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

Str::random 函数生成一个指定长度的随机字符串。这个函数用 PHP 的 random_bytes 函数

use Illuminate\Support\Str;

$random = Str::random(40);

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

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

use Illuminate\Support\Str;

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

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

// 活动将在 8:30 至 9:00 之间进行

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

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

use Illuminate\Support\Str;

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

// a quick brown fox jumps over the lazy dog

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

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

use Illuminate\Support\Str;

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

// the quick brown fox jumps over a lazy dog

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

Str::singular 函数将字符串转换为单数形式。该函数目前仅支持英文:

use Illuminate\Support\Str;

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

// car

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

// child

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

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

use Illuminate\Support\Str;

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

// laravel-5-framework

Str::snake()

Str::snake 方法是将驼峰的函数名或者字符串转换成 _ 命名的函数或者字符串,例如 snakeCase 转换成 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 方法是判断第二个参数是否是第一个参数的开头返回 true or false

use Illuminate\Support\Str;

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

// true

Str::studly()

Str::studly 方法将带有 _的字符串转换成驼峰命名的字符串,与 Str::snake() 相反,例如:

use Illuminate\Support\Str;

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

// FooBar

Str::substr()

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

use Illuminate\Support\Str;

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

// Laravel

Str::title()

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

use Illuminate\Support\Str;

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

// A Nice Title Uses The Correct Case

Str::ucfirst()

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

use Illuminate\Support\Str;

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

// Foo bar

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

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

use Illuminate\Support\Str;

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

// LARAVEL

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

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

use Illuminate\Support\Str;

return (string) Str::uuid();

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

Str::words 方法用于限制字符串中的单词数:

use Illuminate\Support\Str;

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

// Perfectly balanced, as >>>

trans() {#collection-method}

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

echo trans('messages.welcome');

如果指定的翻译键不存在,trans 函数将会返回给定的键。因此在上方的例子中,如果翻译键不存在,trans 函数将返回 messages.welcome

trans_choice() {#collection-method}

trans_choice 函数将根据词形变化来翻译给定的翻译键:

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

如果指定的翻译键不存在,trans_choice 函数将会返回您指定的键。因此,在上方的例子中,若翻译键不存在,则 trans_choice 函数将会返回 messages.notifications

流畅的字符串函数

流畅字符串(Fluent strings)提供了一种更流畅的、拥有面向对象接口形式的字符串,它允许使用比传统字符串操作更具可读性的语法来进行多字符串的链式操作。(译者注:在 7.x 的文档中,该段落的翻译为:总之,「流畅的字符串」 很厉害,妈妈再也不用担心我对字符串操作不顺滑可读性不好而出现问题了。)

after {#collection-method}

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

use Illuminate\Support\Str;

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

// ' my name'

afterLast {#collection-method}

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

use Illuminate\Support\Str;

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

// 'Controller'

append {#collection-method}

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

use Illuminate\Support\Str;

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

// 'Taylor Otwell'

ascii {#collection-method}

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

use Illuminate\Support\Str;

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

// 'u'

basename {#collection-method}

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

use Illuminate\Support\Str;

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

// 'baz'

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

use Illuminate\Support\Str;

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

// 'baz'

before {#collection-method}

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

use Illuminate\Support\Str;

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

// 'This is '

beforeLast {#collection-method}

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

use Illuminate\Support\Str;

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

// 'This '

camel {#collection-method}

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

use Illuminate\Support\Str;

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

// fooBar

contains {#collection-method}

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

use Illuminate\Support\Str;

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

// true

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

use Illuminate\Support\Str;

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

// true

containsAll {#collection-method}

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

use Illuminate\Support\Str;

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

// true

dirname {#collection-method}

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

use Illuminate\Support\Str;

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

// '/foo/bar'

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

use Illuminate\Support\Str;

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

// '/foo'

endsWith {#collection-method}

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

use Illuminate\Support\Str;

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

// true

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

use Illuminate\Support\Str;

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

// true

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

// false

exactly {#collection-method}

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

use Illuminate\Support\Str;

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

// true

explode {#collection-method}

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

use Illuminate\Support\Str;

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

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

finish {#collection-method}

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

use Illuminate\Support\Str;

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

// this/string/

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

// this/string/

is {#collection-method}

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

use Illuminate\Support\Str;

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

// true

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

// false

isAscii {#collection-method}

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

use Illuminate\Support\Str;

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

// true

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

// false

isEmpty {#collection-method}

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

use Illuminate\Support\Str;

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

// true

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

// false

isNotEmpty {#collection-method}

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

use Illuminate\Support\Str;

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

// false

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

// true

kebab {#collection-method}

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

use Illuminate\Support\Str;

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

// foo-bar

length {#collection-method}

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

use Illuminate\Support\Str;

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

// 7

limit {#collection-method}

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

use Illuminate\Support\Str;

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

// The quick brown fox...

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

use Illuminate\Support\Str;

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

// The quick brown fox (...)

lower {#collection-method}

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

use Illuminate\Support\Str;

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

// 'laravel'

ltrim {#collection-method}

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

use Illuminate\Support\Str;

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

// 'Laravel  '

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

// 'Laravel/'

match {#collection-method}

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

use Illuminate\Support\Str;

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

// 'bar'

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

// 'bar'

matchAll {#collection-method}

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

use Illuminate\Support\Str;

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

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

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

use Illuminate\Support\Str;

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

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

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

padBoth {#collection-method}

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

use Illuminate\Support\Str;

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

// '__James___'

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

// '  James   '

padLeft {#collection-method}

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

use Illuminate\Support\Str;

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

// '-=-=-James'

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

// '     James'

padRight {#collection-method}

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

use Illuminate\Support\Str;

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

// 'James-----'

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

// 'James     '

plural {#collection-method}

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

use Illuminate\Support\Str;

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

// cars

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

// children

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

use Illuminate\Support\Str;

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

// children

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

// child

prepend {#collection-method}

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

use Illuminate\Support\Str;

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

// Laravel Framework

replace {#collection-method}

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

use Illuminate\Support\Str;

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

// Laravel 7.x

replaceArray {#collection-method}

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 {#collection-method}

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 {#collection-method}

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 {#collection-method}

replaceMatches 方法用指定字符串替换字符串中使用指定正则表达式匹配到的所有部分:

use Illuminate\Support\Str;

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

// '15015551000'

replaceMatches 方法还接受一个闭包函数,它可作用于字符串中匹配到的每一部分,允许您在闭包函数中处理替换逻辑并返回替换值:

use Illuminate\Support\Str;

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

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

rtrim {#collection-method}

rtrim 方法用于从字符串的右边移除指定字符:

use Illuminate\Support\Str;

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

// '  Laravel'

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

// '/Laravel'

singular {#collection-method}

singular 方法用于将一个字符串转换为其单数形式。该函数仅支持英文:

use Illuminate\Support\Str;

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

// car

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

// child

slug {#collection-method}

slug 方法使用指定字符将字符串格式化为 URL 友好的格式:

use Illuminate\Support\Str;

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

// laravel-framework

snake {#collection-method}

snake 方法用于将字符串转换为 蛇形命名方式

use Illuminate\Support\Str;

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

// foo_bar

split {#collection-method}

split 方法使用正则表达式将字符串分割到集合中:

use Illuminate\Support\Str;

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

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

start {#collection-method}

start 方法用于将某个值添加到字符串的头部,若该字符串没有以此值开头:

use Illuminate\Support\Str;

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

// /this/string

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

// /this/string

startsWith {#collection-method}

startsWith 用于判断字符串是否以指定值开头:

use Illuminate\Support\Str;

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

// true

studly {#collection-method}

studly 方法用于将指定字符串转换为 StudlyCase 形式:

use Illuminate\Support\Str;

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

// FooBar

substr {#collection-method}

substr 方法返回字符串中 start 和 length 的参数指定的字符串部分:

use Illuminate\Support\Str;

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

// Framework

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

// Frame

title {#collection-method}

title 方法将字符串转换为 标题式 表示方法:

use Illuminate\Support\Str;

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

// A Nice Title Uses The Correct Case

trim {#collection-method}

trim 方法用于移除字符串两端的指定字符:

use Illuminate\Support\Str;

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

// 'Laravel'

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

// 'Laravel'

ucfirst {#collection-method}

ucfirst 方法用于将指定字符串转换为首字母大写的形式并将其返回:

use Illuminate\Support\Str;

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

// Foo bar

upper {#collection-method}

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

use Illuminate\Support\Str;

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

// LARAVEL

when {#collection-method}

如果指定条件为 true 时,when 方法将执行指定的闭包函数。闭包函数接受一个流畅字符串实例:

use Illuminate\Support\Str;

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

// 'Taylor Otwell'

如果有必要,您亦可将另一个闭包函数作为 when 方法的第三个参数传递给它。当条件语句的值为 false 时,将执行这个闭包函数。

whenEmpty {#collection-method}

当字符串为空时,whenEmpty 方法将执行指定的闭包函数。若闭包函数返回一个值,则 when 方法也返回这个值。如果闭包函数没有返回任何值,则 when 方法会返回这个流畅字符串实例:

use Illuminate\Support\Str;

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

// 'Laravel'

words {#collection-method}

words 方法用于限制字符串中的单词数:

use Illuminate\Support\Str;

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

// Perfectly balanced, as >>>

URL

action() {#collection-method}

action 方法为指定的控制器的 action 生成一个 URL:

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

您可以将路由参数作为第二个参数传递给这个方法:

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

asset() {#collection-method}

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

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

您可以配置 .env 文件中的 ASSET_URL 变量来设置资产的 URL 主机。当您在诸如 Amazon S3 这样的外部服务上托管您的资产时,这将非常有用:

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

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

route() {#collection-method}

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

$url = route('routeName');

您可以将路由参数作为该函数的第二个参数传递给它:

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

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

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

secure_asset() {#collection-method}

secure_asset 函数将使用 HTTPS 协议为资产生成一个 URL:

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

secure_url() {#collection-method}

secure_url 函数将使用 HTTPS 为指定路径生成一个完整的 URL:

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

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

url() {#collection-method}

url 函数将为指定路径生成一个完整的 URL :

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

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

如果没有指定路径,该方法将会返回一个 Illuminate\Routing\UrlGenerator 实例:

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

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

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

杂项

abort() {#collection-method}

abort 函数抛出 一个 HTTP 异常,该异常将使用 异常处理器 来处理:

abort(403);

您亦可指定异常响应的文本及其响应头:

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

abort_if() {#collection-method}

如果指定的布尔表达式结果为 true 时,abort_if 函数将抛出一个 HTTP 异常:

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

abort 方法类似,您亦可将异常响应文本作为第三个参数,自定义响应头作为第四个参数传递给它:

abort_unless() {#collection-method}

如果指定的布尔表达式结果为 false 时, abort_unless 函数将抛出一个 HTTP 异常:

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

abort 方法类似,您亦可将异常响应文本作为第三个参数,自定义响应头作为第四个参数传递给它:

app() {#collection-method}

app 方法将返回 服务容器 实例:

$container = app();

您亦可传递一个类或接口的名称来从容器中解析它:

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

auth() {#collection-method}

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

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

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

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

back() {#collection-method}

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

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

return back();

bcrypt() {#collection-method}

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

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

blank() {#collection-method}

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

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

// true

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

// false

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

broadcast() {#collection-method}

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

broadcast(new UserRegistered($user));

cache() {#collection-method}

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

$value = cache('key');

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

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

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

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

class_uses_recursive() {#collection-method}

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

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

collect() {#collection-method}

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

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

config() {#collection-method}

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

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

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

你也可以在运行时通过传递一个键/值对数组来设置配置变量:

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

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

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

csrf_field() {#collection-method}

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

{{ csrf_field() }}

csrf_token() {#collection-method}

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

$token = csrf_token();

dd() {#collection-method}

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

dd($value);

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

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

dispatch() {#collection-method}

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

dispatch(new App\Jobs\SendEmails);

dispatch_now() {#collection-method}

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

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

dump() {#collection-method}

dump 打印给定的变量:

dump($value);

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

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

env() {#collection-method}

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

$env = env('APP_ENV');

// Returns 'production' if APP_ENV is not set...
$env = env('APP_ENV', 'production');

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

event() {#collection-method}

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

event(new UserRegistered($user));

filled() {#collection-method}

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

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

// true

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

// false

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

info() {#collection-method}

info 函数将信息写入 log

info('Some helpful information!');

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

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

logger() {#collection-method}

logger 函数可以被用于将 debug 级别的消息写入 log
The logger function can be used to write a debug level message to the log

logger('Debug message');

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

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

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

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

method_field() {#collection-method}

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

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

now() {#collection-method}

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

$now = now();

old() {#collection-method}

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

$value = old('value');

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

optional() {#collection-method}

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

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

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

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

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

policy() {#collection-method}

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

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

redirect() {#collection-method}

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

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

return redirect('/home');

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

report() {#collection-method}

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

report($e);

request() {#collection-method}

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

$request = request();

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

rescue() {#collection-method}

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

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

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

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

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

resolve() {#collection-method}

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

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

response() {#collection-method}

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

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

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

retry() {#collection-method}

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

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

session() {#collection-method}

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

$value = session('key');

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

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

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

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

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

tap() {#collection-method}

tap 函数接受两个参数: 任意 $value 和闭包。 $value 将被传递给闭包,并被 tap 函数返回。与闭包的返回值无关:

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

    $user->save();
});

如果没有向 tap 函数传递闭包,可以调用给定 $value 的任意方法。调用此方法的返回值永远是 $value ,无论方法在其定义中返回什么。例如,Eloquent 的 update 方法指定返回一个整数。但是,我们可以通过 tap 函数链式调用 update 方法强制其返回模型自身:

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

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

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

throw_if() {#collection-method}

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

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

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

throw_unless() {#collection-method}

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

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

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

today() {#collection-method}

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

$today = today();

trait_uses_recursive() {#collection-method}

trait_uses_recursive 返回被 trait 使用的全部 trait

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

transform() {#collection-method}

transform 函数执行基于(非)给定值的 闭包,并返回 闭包 的结果

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

$result = transform(5, $callback);

// 10

还可以传递一个默认值或 闭包 作为该函数的第三个参数。如果给定的值为空时,返回该值:

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

// The value is blank

validator() {#collection-method}

validator 函数根据指定的参数创建一个新的 验证器 实例。方便起见可以用它来代替 Validator facade:

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

value() {#collection-method}

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

$result = value(true);

// true

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

// false

view() {#collection-method}

view 函数获取一个 view 实例:

return view('auth.login');

with() {#collection-method}

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

$callback = function ($value) {
    return (is_numeric($value)) ? $value * 2 : 0;
};

$result = with(5, $callback);

// 10

$result = with(null, $callback);

// 0

$result = with(5, null);

// 5

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册