辅助函数
简介
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::isList Arr::keyBy Arr::last Arr::only Arr::pluck Arr::prepend Arr::pull Arr::query Arr::random Arr::set Arr::shuffle Arr::sort Arr::sortRecursive Arr::toCssClasses Arr::undot Arr::where Arr::whereNotNull 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::excerpt Str::finish Str::headline Str::is Str::isAscii Str::isUuid Str::kebab Str::length Str::limit Str::lower Str::markdown Str::mask Str::orderedUuid Str::padBoth Str::padLeft Str::padRight Str::plural Str::pluralStudly Str::random Str::remove Str::replace Str::replaceArray Str::replaceFirst Str::replaceLast Str::reverse Str::singular Str::slug Str::snake Str::start Str::startsWith Str::studly Str::substr Str::substrCount Str::substrReplace Str::swap Str::title Str::toHtmlString Str::ucfirst Str::upper Str::uuid Str::wordCount Str::words str trans trans_choice
字符流处理
after afterLast append ascii basename before beforeLast between camel contains containsAll dirname endsWith excerpt exactly explode finish is isAscii isEmpty isNotEmpty isUuid kebab length limit lower ltrim markdown mask match matchAll padBoth padLeft padRight pipe plural prepend remove replace replaceArray replaceFirst replaceLast replaceMatches rtrim scan singular slug snake split start startsWith studly substr substrReplace swap tap test title trim ucfirst upper when whenContains whenContainsAll whenEmpty whenNotEmpty whenStartsWith whenEndsWith whenExactly whenIs whenIsAscii whenIsUuid whenTest wordCount words
URLs
action asset route secure_asset secure_url to_route url
其他
abort abort_if abort_unless app auth back bcrypt blank broadcast cache class_uses_recursive collect config cookie csrf_field csrf_token decrypt dd dispatch dump encrypt 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()
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()
如果给定的键在数组中不存在或给定的键的值被设置为 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()
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
,如果数组没有以零开头的连续数字键,则将其视为「关联」:
use Illuminate\Support\Arr;
$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
// true
$isAssoc = Arr::isAssoc([1, 2, 3]);
// false
Arr::isList()
如果给定数组的键是从零开始的连续整数,则 Arr::isList
方法返回 true
:
use Illuminate\Support\Arr;
$isAssoc = Arr::isList(['foo', 'bar', 'baz']);
// true
$isAssoc = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]);
// false
Arr::keyBy()
注意:自 Laravel 9.2 引入
The Arr::keyBy
method keys the array by the given key. If multiple items have the same key, only the last one will appear in the new array:
use Illuminate\Support\Arr;
$array = [
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
];
$keyed = Arr::keyBy($array, 'product_id');
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
Arr::last()
Arr::last
函数返回数组中满足指定条件的最后一个元素:
use Illuminate\Support\Arr;
$array = [100, 200, 300, 110];
$last = Arr::last($array, function ($value, $key) {
return $value >= 150;
});
// 300
将默认值作为第三个参数传递给该方法,如果没有值满足条件,则返回该默认值:
use Illuminate\Support\Arr;
$last = Arr::last($array, $callback, $default);
Arr::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::toCssClasses()
Arr::toCssClasses
函数根据给定的条件编译并返回 CSS 类字符串。该方法接受一个类数组,其中数组键包含你希望添加的一个或多个 CSS Class,而值是一个布尔表达式。如果数组元素有一个数字键,它将始终包含在呈现的类列表中:
use Illuminate\Support\Arr;
$isActive = false;
$hasError = true;
$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError];
$classes = Arr::toCssClasses($array);
/*
'p-4 bg-red'
*/
Laravel 基于该函数实现条件类 以及 @class
Blade 指令。
Arr::undot()
Arr::undot
函数将使用「点表示法」的一维数组扩展为多维数组:
use Illuminate\Support\Arr;
$array = [
'user.name' => 'Kevin Malone',
'user.occupation' => 'Accountant',
];
$array = Arr::undot($array);
// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]
Arr::where()
Arr::where
函数使用给定的回调函数返回的结果过滤数组:
use Illuminate\Support\Arr;
$array = [100, '200', 300, '400', 500];
$filtered = Arr::where($array, function ($value, $key) {
return is_string($value);
});
// [1 => '200', 3 => '400']
Arr::whereNotNull()
Arr::whereNotNull
函数将从给定数组中删除所有 null
值:
use Illuminate\Support\Arr;
$array = [0, null];
$filtered = Arr::whereNotNull($array);
// [0 => 0]
Arr::wrap()
Arr::wrap
函数可以将给定值转换为一个数组,如果给定的值已经是一个数组,它将原样返回:
use Illuminate\Support\Arr;
$string = 'Laravel';
$array = Arr::wrap($string);
// ['Laravel']
如果给定值是 null
,将返回一个空数组:
use Illuminate\Support\Arr;
$array = Arr::wrap(null);
// []
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
该函数也接受一个默认值,如果没有找到指定的键,将返回默认值:
$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_get
一样, 函数也支持使用「*」作为通配符给相应键名赋值:
$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, $overwrite = 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 函数来生成应用目录下特定文件的完整路径:
$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)的路径,便于加载 css,js 等静态文件:
$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
目录的完整路径。你也可以用resource_path
函数来生成位于资源路径中的特定文件路径:
$path = resource_path();
$path = resource_path('sass/app.scss');
storage_path()
storage_path
函数返回 storage
目录的完整路径。 你也可以用storage_path
函数来生成位于资源路径中的特定文件路径:
$path = storage_path();
$path = storage_path('app/file.txt');