【laravel7.x中文文档】辅助函数

辅助函数

[TOC]

简介

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

可用方法

数组 & 对象

Arr::add
Arr::collapse
Arr::crossJoin
Arr::divide
Arr::dot
Arr::except
Arr::first
Arr::flatten
Arr::forget
Arr::get
Arr::has
Arr::isAssoc
Arr::last
Arr::only
Arr::pluck
Arr::prepend
Arr::pull
Arr::random
Arr::query
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::before
Str::beforeLast
Str::camel
Str::contains
Str::containsAll
Str::endsWith
Str::finish
Str::is
Str::isUuid
Str::kebab
Str::limit
Str::orderedUuid
Str::plural
Str::random
Str::replaceArray
Str::replaceFirst
Str::replaceLast
Str::singular
Str::slug
Str::snake
Str::start
Str::startsWith
Str::studly
Str::title
Str::ucfirst
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
kebab
length
limit
lower
match
matchAll
plural
prepend
replace
replaceArray
replaceFirst
replaceLast
replaceMatches
start
upper
title
singular
slug
snake
startsWith
studly
substr
trim
ucfirst
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
decrypt
dispatch
dispatch_now
dump
encrypt
env
event
factory
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::add() {#collection-method .first-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::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::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::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::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::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 函数去生成 database 目录下一个指定文件的完整路径:

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

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键值不存在,则返回messages.welcome

class_basename()

class_basename 函数返回删除命名空间后的类名:

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

// Baz

e()

e 函数在指定字符串上运行 htmlentities方法(double_encode参数为false):

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

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

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'

【【laravel7.x中文文档】辅助函数隶属于分类: php laravel

它起初由本站用户:刘欣Eden于4年前 创建。

它被收录于如下合集: Laravel7中文文档

该内容的链接是:

目录