# 輔助函數
- [簡介](#introduction)
- [可用方法](#available-methods)
<a name="introduction"></a>
## 簡介
Laravel 包含各種各樣的「全局」PHP輔助函數,框架本身也大量的使用了這些功能函數;如果你覺的方便,你可以在你的應用中任意使用這些函數
<a name="available-methods"></a>
## 可用方法
<style>
.collection-method-list > p {
column-count: 3; -moz-column-count: 3; -webkit-column-count: 3;
column-gap: 2em; -moz-column-gap: 2em; -webkit-column-gap: 2em;
}
.collection-method-list a {
display: block;
}
</style>
### 數組 & 對象
<div class="collection-method-list" markdown="1">
[Arr::add](#method-array-add)
[Arr::collapse](#method-array-collapse)
[Arr::divide](#method-array-divide)
[Arr::dot](#method-array-dot)
[Arr::except](#method-array-except)
[Arr::first](#method-array-first)
[Arr::flatten](#method-array-flatten)
[Arr::forget](#method-array-forget)
[Arr::get](#method-array-get)
[Arr::has](#method-array-has)
[Arr::last](#method-array-last)
[Arr::only](#method-array-only)
[Arr::pluck](#method-array-pluck)
[Arr::prepend](#method-array-prepend)
[Arr::pull](#method-array-pull)
[Arr::random](#method-array-random)
[Arr::set](#method-array-set)
[Arr::sort](#method-array-sort)
[Arr::sortRecursive](#method-array-sort-recursive)
[Arr::where](#method-array-where)
[Arr::wrap](#method-array-wrap)
[data_fill](#method-data-fill)
[data_get](#method-data-get)
[data_set](#method-data-set)
[head](#method-head)
[last](#method-last)
</div>
### 路徑
<div class="collection-method-list" markdown="1">
[app_path](#method-app-path)
[base_path](#method-base-path)
[config_path](#method-config-path)
[database_path](#method-database-path)
[mix](#method-mix)
[public_path](#method-public-path)
[resource_path](#method-resource-path)
[storage_path](#method-storage-path)
</div>
### 字符串
<div class="collection-method-list" markdown="1">
[\__](#method-__)
[Str::camel](#method-camel-case)
[class_basename](#method-class-basename)
[e](#method-e)
[Str::endsWith](#method-ends-with)
[Str::kebab](#method-kebab-case)
[preg_replace_array](#method-preg-replace-array)
[Str::snake](#method-snake-case)
[Str::startsWith](#method-starts-with)
[Str::after](#method-str-after)
[Str::before](#method-str-before)
[Str::contains](#method-str-contains)
[Str::finish](#method-str-finish)
[Str::is](#method-str-is)
[Str::limit](#method-str-limit)
[Str::orderedUuid](#method-str-ordered-uuid)
[Str::plural](#method-str-plural)
[Str::random](#method-str-random)
[Str::replaceArray](#method-str-replace-array)
[Str::replaceFirst](#method-str-replace-first)
[Str::replaceLast](#method-str-replace-last)
[Str::singular](#method-str-singular)
[Str::slug](#method-str-slug)
[Str::start](#method-str-start)
[Str::studly](#method-studly-case)
[Str::title](#method-title-case)
[trans](#method-trans)
[trans_choice](#method-trans-choice)
[Str::uuid](#method-str-uuid)
</div>
### URLs
<div class="collection-method-list" markdown="1">
[action](#method-action)
[asset](#method-asset)
[secure_asset](#method-secure-asset)
[route](#method-route)
[secure_url](#method-secure-url)
[url](#method-url)
</div>
### 其他
<div class="collection-method-list" markdown="1">
[abort](#method-abort)
[abort_if](#method-abort-if)
[abort_unless](#method-abort-unless)
[app](#method-app)
[auth](#method-auth)
[back](#method-back)
[bcrypt](#method-bcrypt)
[blank](#method-blank)
[broadcast](#method-broadcast)
[cache](#method-cache)
[class_uses_recursive](#method-class-uses-recursive)
[collect](#method-collect)
[config](#method-config)
[cookie](#method-cookie)
[csrf_field](#method-csrf-field)
[csrf_token](#method-csrf-token)
[dd](#method-dd)
[decrypt](#method-decrypt)
[dispatch](#method-dispatch)
[dispatch_now](#method-dispatch-now)
[dump](#method-dump)
[encrypt](#method-encrypt)
[env](#method-env)
[event](#method-event)
[factory](#method-factory)
[filled](#method-filled)
[info](#method-info)
[logger](#method-logger)
[method_field](#method-method-field)
[now](#method-now)
[old](#method-old)
[optional](#method-optional)
[policy](#method-policy)
[redirect](#method-redirect)
[report](#method-report)
[request](#method-request)
[rescue](#method-rescue)
[resolve](#method-resolve)
[response](#method-response)
[retry](#method-retry)
[session](#method-session)
[tap](#method-tap)
[today](#method-today)
[throw_if](#method-throw-if)
[throw_unless](#method-throw-unless)
[trait_uses_recursive](#method-trait-uses-recursive)
[transform](#method-transform)
[validator](#method-validator)
[value](#method-value)
[view](#method-view)
[with](#method-with)
</div>
<a name="method-listing"></a>
## 方法列表
<style>
#collection-method code {
font-size: 14px;
}
#collection-method:not(.first-collection-method) {
margin-top: 50px;
}
</style>
<a name="arrays"></a>
## 數組 & 對象
<a name="method-array-add"></a>
#### `Arr::add()` {#collection-method .first-collection-method}
如果給定的鍵不存在數組中,那么 `Arr::add` 函數將會把給定的鍵/值對添加到數組中:
use Illuminate\Support\Arr;
$array = Arr::add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
<a name="method-array-collapse"></a>
#### `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]
<a name="method-array-divide"></a>
#### `Arr::divide()` {#collection-method}
`Arr::divide` 函數返回一個二維數組,一個值包含原始數組的鍵,另一個值包含原始數組的值:
use Illuminate\Support\Arr;
[$keys, $values] = Arr::divide(['name' => 'Desk']);
// $keys: ['name'] 多維數組中的第0個值
// $values: ['Desk'] 多維數組中的第1個值
<a name="method-array-dot"></a>
#### `Arr::dot()` {#collection-method}
`Arr::dot` 函數將多維數組中所有的鍵平鋪到一維數組中,新數組使用「.」符號表示層級包含關系:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
$flattened = Arr::dot($array);
// ['products.desk.price' => 100]
<a name="method-array-except"></a>
#### `Arr::except()` {#collection-method}
`Arr::except` 函數從數組中刪除給定的鍵/值對:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100];
$filtered = Arr::except($array, ['price']);
// ['name' => 'Desk']
<a name="method-array-first"></a>
#### `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);
<a name="method-array-flatten"></a>
#### `Arr::flatten()` {#collection-method}
`Arr::flatten` 函數將多維數組中數組的值取出平鋪為一維數組:
use Illuminate\Support\Arr;
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$flattened = Arr::flatten($array);
// ['Joe', 'PHP', 'Ruby']
<a name="method-array-forget"></a>
#### `Arr::forget()` {#collection-method}
`Arr::forget` 函數使用「.」符號從深度嵌套的數組中刪除給定的鍵/值對:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::forget($array, 'products.desk');
// ['products' => []]
<a name="method-array-get"></a>
#### `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
<a name="method-array-has"></a>
#### `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
<a name="method-array-last"></a>
#### `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);
<a name="method-array-only"></a>
#### `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]
<a name="method-array-pluck"></a>
#### `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']
<a name="method-array-prepend"></a>
#### `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]
<a name="method-array-pull"></a>
#### `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);
<a name="method-array-random"></a>
#### `Arr::random()` {#collection-method}
`Arr::random` 函數從數組中隨機返回一個值:
use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 4 - (隨機檢索)
你也可以將返回值的數量作為可選的第二個參數傳遞給該方法,請注意,提供這個參數會返回一個數組,即便是你只需要一項:
use Illuminate\Support\Arr;
$items = Arr::random($array, 2);
// [2, 5] - (隨機檢索)
<a name="method-array-set"></a>
#### `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]]]
<a name="method-array-sort"></a>
#### `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'],
]
*/
<a name="method-array-sort-recursive"></a>
#### `Arr::sortRecursive()` {#collection-method}
`Arr::sortRecursive` 函數使用 `sort` 函數對數組進行遞歸排序:
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'],
]
*/
<a name="method-array-where"></a>
#### `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']
<a name="method-array-wrap"></a>
#### `Arr::wrap()` {#collection-method}
`Arr::wrap` 函數將給定的值變為一個數組, 如果給定的值已經是數組,則不改變:
use Illuminate\Support\Arr;
$string = 'Laravel';
$array = Arr::wrap($string);
// ['Laravel']
如果給定的值是空,則返回一個空數組:
use Illuminate\Support\Arr;
$nothing = null;
$array = Arr::wrap($nothing);
// []
<a name="method-data-fill"></a>
#### `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],
],
]
*/
<a name="method-data-get"></a>
#### `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'];
<a name="method-data-set"></a>
#### `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]]]
<a name="method-head"></a>
#### `head()` {#collection-method}
`head` 函數返回給定數組中的第一個元素:
$array = [100, 200, 300];
$first = head($array);
// 100
<a name="method-last"></a>
#### `last()` {#collection-method}
`last` 函數返回給定數組中的最后一個元素:
$array = [100, 200, 300];
$last = last($array);
// 300
<a name="paths"></a>
## 路徑
<a name="method-app-path"></a>
#### `app_path()` {#collection-method}
`app_path` 函數返回 `app` 目錄的完整路徑.你也可以使用 `app_path` 函數來設置應用程序 `app` 目錄的完整路徑:
$path = app_path();
$path = app_path('Http/Controllers/Controller.php');
<a name="method-base-path"></a>
#### `base_path()` {#collection-method}
`base_path` 函數返回項目根目錄的完整路徑.你也可以使用 `base_path` 函數設置項目根目錄的完整路徑:
$path = base_path();
$path = base_path('vendor/bin');
<a name="method-config-path"></a>
#### `config_path()` {#collection-method}
`config_path` 函數返回 `config`目錄的完整路徑.你也可以使用 `config_path` 函數設置應用程序 `config` 目錄中給定文件的完整路徑:
$path = config_path();
$path = config_path('app.php');
<a name="method-database-path"></a>
#### `database_path()` {#collection-method}
`database_path` 函數返回 `database` 目錄的完整路徑.你也可以使用 `database_path` 函數來設置 `database` 目錄中給定文件的完整路徑:
$path = database_path();
$path = database_path('factories/UserFactory.php');
<a name="method-mix"></a>
#### `mix()` {#collection-method}
`mix` 函數返回 [版本化 Mix 文件](/docs/{{version}}/mix) 的路徑:
$path = mix('css/app.css');
<a name="method-public-path"></a>
#### `public_path()` {#collection-method}
`public_path` 函數返回 `public` 目錄的完整路徑.你也可以使用 `public_path` 函數來生成 `public` 目錄中給定文件的完整路徑:
$path = public_path();
$path = public_path('css/app.css');
<a name="method-resource-path"></a>
#### `resource_path()` {#collection-method}
`resource_path` 函數返回 `resources` 目錄的完整路徑.你也可以使用 `resource_path` 函數來生成資源文件中給定文件的完整路徑
$path = resource_path();
$path = resource_path('sass/app.scss');
<a name="method-storage-path"></a>
#### `storage_path()` {#collection-method}
`storage_path` 函數返回 `storage` 目錄的完整路徑.你也可以使用 `storage_path` 函數來設置存儲目錄下指定文件的完整路徑 :
$path = storage_path();
$path = storage_path('app/file.txt');
<a name="strings"></a>
## 字符串
<a name="method-__"></a>
#### `__()` {#collection-method}
`__` 函數使用你的[本地化文件](/docs/{{version}}/localization)來翻譯給定的翻譯字符串或翻譯鍵:
echo __('Welcome to our application');
echo __('messages.welcome');
如果指定的翻譯字符串或翻譯鍵不存在, `__` 函數將返回給定的值.所以,按照上面的例子,如果翻譯鍵 `messages.welcome` 不存在, `__` 函數會將其直接返回.
<a name="method-camel-case"></a>
#### `Str::camel()` {#collection-method}
The `Str::camel` method converts the given string to `camelCase`:
`Str::camel` 函數將給定字符串「蛇式」轉化為 `camelCase`「駝峰式」:
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// fooBar
<a name="method-class-basename"></a>
#### `class_basename()` {#collection-method}
`class_basename` 函數返回被刪除了命名空間的指定類的類名:
$class = class_basename('Foo\Bar\Baz');
// Baz
<a name="method-e"></a>
#### `e()` {#collection-method}
`e` 函數將默認值為 `true`的 `double_encode` 選項值改為`false` 來運行 `PHP` 的 `htmlspecialchars`函數 :
echo e('<html>foo</html>');
// <html>foo</html>
<a name="method-ends-with"></a>
#### `Str::endsWith()` {#collection-method}
`Str::endsWith` 函數判斷指定的字符串是否以給定的值結尾:
$result = Str::endsWith('This is my name', 'name');
// true
<a name="method-kebab-case"></a>
#### `Str::kebab()` {#collection-method}
`Str::kebab` 函數將給定的「駝峰式」字符串轉化為 `kebab-case`「短橫式」字符串:
use Illuminate\Support\Str;
$converted = Str::kebab('fooBar');
// foo-bar
<a name="method-preg-replace-array"></a>
#### `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);
// 活動將在 8:30 至 9:00 之間進行
<a name="method-snake-case"></a>
#### `Str::snake()` {#collection-method}
`Str::snake` 函數將給定的字符串轉換為 `snake_case`「蛇式」:
use Illuminate\Support\Str;
$converted = Str::snake('fooBar');
// foo_bar
<a name="method-starts-with"></a>
#### `Str::startsWith()` {#collection-method}
`Str::startsWith` 函數判斷給定的字符串的開頭是否是指定值:
use Illuminate\Support\Str;
$result = Str::startsWith('This is my name', 'This');
// true
<a name="method-str-after"></a>
#### `Str::after()` {#collection-method}
`Str::after` 函數返回在字符串中指定值之后的所有內容:
use Illuminate\Support\Str;
$slice = Str::after('This is my name', 'This is');
// ' my name'
<a name="method-str-before"></a>
#### `Str::before()` {#collection-method}
`Str::before` 函數返回在字符串中指定值之前的所有內容:
use Illuminate\Support\Str;
$slice = Str::before('This is my name', 'my name');
// 'This is '
<a name="method-str-contains"></a>
#### `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
<a name="method-str-finish"></a>
#### `Str::finish()` {#collection-method}
`Str::finish` 函數將給定的字符串以給定的值結尾返回(如果它尚未以給定值結尾):
use Illuminate\Support\Str;
$adjusted = Str::finish('this/string', '/');
// this/string/
$adjusted = Str::finish('this/string/', '/');
// this/string/
<a name="method-str-is"></a>
#### `Str::is()` {#collection-method}
`Str::is` 函數判斷給定的字符串是否匹配給定的模式。星號 * 可以用來表示通配符:
use Illuminate\Support\Str;
$matches = Str::is('foo*', 'foobar');
// true
$matches = Str::is('baz*', 'foobar');
// false
<a name="method-str-limit"></a>
#### `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 (...)
<a name="method-str-ordered-uuid"></a>
#### `Str::orderedUuid()` {#collection-method}
The `Str::orderedUuid` 方法高效生成一個可存儲在索引數據庫列中的「第一時間」 UUID:
use Illuminate\Support\Str;
return (string) Str::orderedUuid();
<a name="method-str-plural"></a>
#### `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
<a name="method-str-random"></a>
#### `Str::random()` {#collection-method}
`Str::random` 函數生成一個指定長度的隨機字符串。這個函數用 PHP 的 `random_bytes` 函數:
use Illuminate\Support\Str;
$random = Str::random(40);
<a name="method-str-replace-array"></a>
#### `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);
// The event will take place between 8:30 and 9:00
<a name="method-str-replace-first"></a>
#### `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
<a name="method-str-replace-last"></a>
#### `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
<a name="method-str-singular"></a>
#### `Str::singular()` {#collection-method}
`Str::singular` 函數將字符串轉換為單數形式。該函數目前僅支持英文:
use Illuminate\Support\Str;
$singular = Str::singular('cars');
// car
$singular = Str::singular('children');
// child
<a name="method-str-slug"></a>
#### `Str::slug()` {#collection-method}
`Str::slug` 函數將給定的字符串生成一個 URL 友好的 「slug」 :
use Illuminate\Support\Str;
$slug = Str::slug('Laravel 5 Framework', '-');
// laravel-5-framework
<a name="method-str-start"></a>
#### `Str::start()` {#collection-method}
`Str::start` 函數將給定值添加到給定字符串的開始位置(如果字符串尚未以給定值開始):
use Illuminate\Support\Str;
$adjusted = Str::start('this/string', '/');
// /this/string
$adjusted = Str::start('/this/string', '/');
// /this/string
<a name="method-studly-case"></a>
#### `Str::studly()` {#collection-method}
`Str::studly` 函數將給定的字符串轉換為 「變種駝峰命名」:
use Illuminate\Support\Str;
$converted = Str::studly('foo_bar');
// FooBar
<a name="method-title-case"></a>
#### `Str::title()` {#collection-method}
`Str::title` 函數將給定的字符串轉換為「首字母大寫」:
use Illuminate\Support\Str;
$converted = Str::title('a nice title uses the correct case');
// A Nice Title Uses The Correct Case
<a name="method-trans"></a>
#### `trans()` {#collection-method}
`trans` 函數使用你的 [本地文件](/docs/{{version}}/localization) 轉換給定的翻譯密鑰:
echo trans('messages.welcome');
如果指定的翻譯鍵不存在,則 `trans` 方法會簡單地返回給定的鍵。所以,就上面的例子而言,如果翻譯鍵不存在, `trans` 方法會返回 `messages.welcome` 。
<a name="method-trans-choice"></a>
#### `trans_choice()` {#collection-method}
`trans_choice` 函數根據詞形變化來翻譯給定的翻譯鍵:
echo trans_choice('messages.notifications', $unreadCount);
如果指定的翻譯鍵不存在, `trans_choice` 方法會簡單地返回給定的鍵。所以,按照上面的例子,如果翻譯鍵不存在, `trans_choice` 方法會返回 `messages.notifications` 。
<a name="method-str-uuid"></a>
#### `Str::uuid()` {#collection-method}
`Str::uuid` 方法生成一個 UUID(版本 4):
use Illuminate\Support\Str;
return (string) Str::uuid();
<a name="urls"></a>
## URLs
<a name="method-action"></a>
#### `action()` {#collection-method}
`action` 函數為指定的控制器動作生成一個 URL 。你不需要傳遞完整的控制器命名空間。只需要傳遞相對于 `App\Http\Controllers` 命名空間控制器類名稱:
$url = action('HomeController@index');
$url = action([HomeController::class, 'index']);
如果該方法接受路由參數,則可以將它們作為方法的第二個參數傳遞:
$url = action('UserController@profile', ['id' => 1]);
<a name="method-asset"></a>
#### `asset()` {#collection-method}
`asset` 函數使用當前請求的協議( HTTP 或 HTTPS )為資源文件生成 URL :
$url = asset('img/photo.jpg');
您可以通過 `ASSET_URL` 在 `.env` 文件中設置變量來配置資產URL主機。如果您在 Amazon S3 等外部服務上托管資產,這將非常有用:
// ASSET_URL=http://example.com/assets
$url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpg
<a name="method-secure-asset"></a>
#### `secure_asset()` {#collection-method}
`secure_asset` 函數使用 HTTPS 協議為資源文件生成 URL:
$url = secure_asset('img/photo.jpg');
<a name="method-route"></a>
#### `route()` {#collection-method}
`route` 函數為給定的命名路由生成一個 URL :
$url = route('routeName');
如果路由接受參數,則可以將它們作為方法的第二個參數傳遞:
$url = route('routeName', ['id' => 1]);
默認情況下, `route` 函數生成的是絕對 URL 。如果你想生成一個相對 URL ,你可以傳遞 `false` 作為第三個參數:
$url = route('routeName', ['id' => 1], false);
<a name="method-secure-url"></a>
#### `secure_url()` {#collection-method}
`secure_url` 函數為給定的路徑生成一個標準的 HTTPS URL :
$url = secure_url('user/profile');
$url = secure_url('user/profile', [1]);
<a name="method-url"></a>
#### `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();
<a name="miscellaneous"></a>
## 其他
<a name="method-abort"></a>
#### `abort()` {#collection-method}
`abort` 函數拋出 [異常處理](/docs/{{version}}/errors#the-exception-handler) 程序呈現的 [ HTTP 異常 ](/docs/{{version}}/errors#http-exceptions) :
abort(403);
你也可以提供額外的響應文本和自定義響應標頭:
abort(403, 'Unauthorized.', $headers);
<a name="method-abort-if"></a>
#### `abort_if()` {#collection-method}
如果給定的布爾表達式計算結果為 `true`, `abort_if` 函數將拋出一個 HTTP 異常:
abort_if(! Auth::user()->isAdmin(), 403);
和 `abort` 方法一樣,你也可以提供異常的響應文本作為第三個參數,并提供一個自定義響應頭數據作為第四個參數。
<a name="method-abort-unless"></a>
#### `abort_unless()` {#collection-method}
如果給定的布爾表達式計算結果為 `false`, `abort_unless` 函數將拋出一個 HTTP 異常:
abort_unless(Auth::user()->isAdmin(), 403);
和 `abort` 方法一樣,你也可以提供異常的響應文本作為第三個參數,并提供一個自定義響應頭數組作為第四個參數。
<a name="method-app"></a>
#### `app()` {#collection-method}
`app` 函數返回 [服務容器](/docs/{{version}}/container) 實例:
$container = app();
你可以傳遞一個類或接口名稱來從容器中解析它:
$api = app('HelpSpot\API');
<a name="method-auth"></a>
#### `auth()` {#collection-method}
`auth` 函數返回一個 [認證](/docs/{{version}}/authentication) 實例。為了方便起見,你可以使用它來替代 `Auth` Facade :
$user = auth()->user();
如果需要,你可以指定你想要訪問的認證實例:
$user = auth('admin')->user();
<a name="method-back"></a>
#### `back()` {#collection-method}
`back` 函數生成一個 [重定向 HTTP 響應](/docs/{{version}}/responses#redirects) 到用戶之前的位置:
return back($status = 302, $headers = [], $fallback = false);
return back();
<a name="method-bcrypt"></a>
#### `bcrypt()` {#collection-method}
`bcrypt` [哈希](/docs/{{version}}/hashing) 使用 Bcrypt 對給定的值進行散列。你可以使用它替代 `Hash` Facade :
$password = bcrypt('my-secret-password');
<a name="method-broadcast"></a>
#### `broadcast()` {#collection-method}
`broadcast` 函數將 [廣播](/docs/{{version}}/broadcasting) 給定的 [事件](/docs/{{version}}/events) 到它的監聽器:
broadcast(new UserRegistered($user));
<a name="method-blank"></a>
#### `blank()` {#collection-method}
`blank` 函數判斷給定的值是否為空:
blank('');
blank(' ');
blank(null);
blank(collect());
// true
blank(0);
blank(true);
blank(false);
// false
如果想使用與 `blank` 函數相反的方法,請看 [`filled`](#method-filled) 方法。
<a name="method-cache"></a>
#### `cache()` {#collection-method}
`cache` 函數可以從 [緩存](/docs/{{version}}/cache) 中獲取值.如果緩存中給定的鍵不存在,將返回一個可選的默認值:
$value = cache('key');
$value = cache('key', 'default');
你可以通過向函數添加鍵值對數組來設置緩存項。與此同時,你還應該傳遞有效的分鐘數或者緩存的持續時間來設置緩存過期時間 :
cache(['key' => 'value'], 5);
cache(['key' => 'value'], now()->addSeconds(10));
<a name="method-class-uses-recursive"></a>
#### `class_uses_recursive()` {#collection-method}
`class_uses_recursive` 函數返回一個類使用的所有 traits ,包括它所有父類使用的 traits:
$traits = class_uses_recursive(App\User::class);
<a name="method-collect"></a>
#### `collect()` {#collection-method}
`collect` 函數根據給定的值創建一個 [collection](/docs/{{version}}/collections) 實例。
$collection = collect(['taylor', 'abigail']);
<a name="method-config"></a>
#### `config()` {#collection-method}
`config` 函數獲取 [configuration](/docs/{{version}}/configuration) 變量的值。可以使用「點」語法訪問配置的值,其中包括文件的名稱和訪問的選項,如果訪問的配置選項不存在,你可以指定一個默認值并且返回這個默認值:
$value = config('app.timezone');
$value = config('app.timezone', $default);
你也可以在運行時通過傳遞一個鍵/值對數組來設置配置變量:
config(['app.debug' => true]);
<a name="method-cookie"></a>
#### `cookie()` {#collection-method}
`cookie` 函數創建一個新的 [cookie](/docs/{{version}}/requests#cookies) 實例:
$cookie = cookie('name', 'value', $minutes);
<a name="method-csrf-field"></a>
#### `csrf_field()` {#collection-method}
`csrf_field` 函數生成一個包含 CSRF 令牌值的 HTML 輸入表單字段 `hidden` 。例如,使用 [Blade 語法](/docs/{{version}}/blade):
{{ csrf_field() }}
<a name="method-csrf-token"></a>
#### `csrf_token()` {#collection-method}
`csrf_token` 函數獲取當前CSRF令牌的值:
$token = csrf_token();
<a name="method-dd"></a>
#### `dd()` {#collection-method}
`dd` 函數打印輸出給定的變量并且結束腳本運行:
dd($value);
dd($value1, $value2, $value3, ...);
如果你不停止執行腳本,那么可以使用 [`dump`](#method-dump) 函數。
<a name="method-decrypt"></a>
#### `decrypt()` {#collection-method}
`decrypt` 函數可以使用 Laravel 的 [加密解密機制](/docs/{{version}}/encryption):
$decrypted = decrypt($encrypted_value);
<a name="method-dispatch"></a>
#### `dispatch()` {#collection-method}
`dispatch` 函數將給定的 [任務](/docs/{{version}}/queues#creating-jobs) 推送到 Laravel [任務隊列](/docs/{{version}}/queues)中:
dispatch(new App\Jobs\SendEmails);
<a name="method-dispatch-now"></a>
#### `dispatch_now()` {#collection-method}
`dispatch_now` 函數立即運行給定的 [任務](/docs/{{version}}/queues#creating-jobs) 并從 `handle` 方法返回值:
$result = dispatch_now(new App\Jobs\SendEmails);
<a name="method-dump"></a>
#### `dump()` {#collection-method}
`dump` 打印給定的變量:
dump($value);
dump($value1, $value2, $value3, ...);
如果你想要在打印后停止執行腳本,可以使用 [`dd`](#method-dd) 函數。
> {提示}你可以使用 Artisan 中的 `dump-server` 命令攔截所有的 `dump` 調用并把它們顯示在控制臺窗口而不是瀏覽器中。
<a name="method-encrypt"></a>
#### `encrypt()` {#collection-method}
`encrypt` 函數使用 Laravel 的[加解密機制](/docs/{{version}}/encryption) 對給定的值進行加密:
$encrypted = encrypt($unencrypted_value);
<a name="method-env"></a>
#### `env()` {#collection-method}
`env` 函數可以獲取[環境變量](/docs/{{version}}/configuration#environment-configuration) 配置的值或者返回默認值:
$env = env('APP_ENV');
// 返回 'production' 如果 APP_ENV 未設置的話...
$env = env('APP_ENV', 'production');
> {注意} 如果你在部署過程中執行了 `config:cache` 命令 ,那么你應該確保只從配置文件中調用 `env` 函數.一旦配置被緩存,`.env` 文件將不再次加載,所有對 `env` 函數的調用將返回 `null`。
<a name="method-event"></a>
#### `event()` {#collection-method}
`event` 函數向監聽器派發給定 [事件](/docs/{{version}}/events) :
event(new UserRegistered($user));
<a name="method-factory"></a>
#### `factory()` {#collection-method}
`factory` 函數根據給定的類、名稱和數量創建模型工廠構造器。它能夠被用于 [測試](/docs/{{version}}/database-testing#writing-factories) 或 [數據填充](/docs/{{version}}/seeding#using-model-factories):
$user = factory(App\User::class)->make();
<a name="method-filled"></a>
#### `filled()` {#collection-method}
`filled` 函數返回是否不為「空」:
filled(0);
filled(true);
filled(false);
// true
filled('');
filled(' ');
filled(null);
filled(collect());
// false
[`blank`](#method-blank) 方法與 `filled` 作用相反。
<a name="method-info"></a>
#### `info()` {#collection-method}
`info` 函數將信息寫入 [log](/docs/{{version}}/logging):
info('Some helpful information!');
可以將上下文數據數組傳遞給此函數:
info('User login attempt failed.', ['id' => $user->id]);
<a name="method-logger"></a>
#### `logger()` {#collection-method}
`logger` 函數可以被用于將 `debug` 級別的消息寫入 [log](/docs/{{version}}/logging):
logger('Debug message');
可以將上下文數據數組傳遞給此函數:
logger('User has logged in.', ['id' => $user->id]);
如果不帶參數調用此函數,它將返回 [logger](/docs/{{version}}/errors#logging) 實例:
logger()->error('You are not allowed here.');
<a name="method-method-field"></a>
#### `method_field()` {#collection-method}
`method_field` 行數生成包含模仿表單 HTTP 動作的 HTML `hidden` 域。下面的例子使用了 [Blade 語法](/docs/{{version}}/blade):
<form method="POST">
{{ method_field('DELETE') }}
</form>
<a name="method-now"></a>
#### `now()` {#collection-method}
`now` 函數根據當前時間創建一個新的 `Illuminate\Support\Carbon` 實例:
$now = now();
<a name="method-old"></a>
#### `old()` {#collection-method}
`old` 函數 [獲取](/docs/{{version}}/requests#retrieving-input) 刷入 session 的 [舊的輸入值](/docs/{{version}}/requests#old-input) :
$value = old('value');
$value = old('value', 'default');
<a name="method-optional"></a>
#### `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 DummyUser;
});
<a name="method-policy"></a>
#### `policy()` {#collection-method}
`policy` 方法為給定的類獲取 [policy](/docs/{{version}}/authorization#creating-policies) 實例:
$policy = policy(App\User::class);
<a name="method-redirect"></a>
#### `redirect()` {#collection-method}
`redirect` 函數返回 [重定向 HTTP 響應](/docs/{{version}}/responses#redirects),如果不帶參數調用則返回重定向器實例:
return redirect($to = null, $status = 302, $headers = [], $secure = null);
return redirect('/home');
return redirect()->route('route.name');
<a name="method-report"></a>
#### `report()` {#collection-method}
`report` 函數使用 [異常處理器](/docs/{{version}}/errors#the-exception-handler) 的 `report` 方法報告異常:
report($e);
<a name="method-request"></a>
#### `request()` {#collection-method}
`request` 函數返回當前 [請求](/docs/{{version}}/requests) 實例,或者獲取一個輸入項:
$request = request();
$value = request('key', $default);
<a name="method-rescue"></a>
#### `rescue()` {#collection-method}
`rescue` 函數執行給定的閉包,并且捕獲其執行過程中引發的任何異常。捕獲的所有異常都將傳遞給 [異常處理器](/docs/{{version}}/errors#the-exception-handler) 的 `report` 方法;然后繼續處理此次請求:
return rescue(function () {
return $this->method();
});
還可以為其傳遞第二個參數。這個參數將作為執行閉包引發異常時的 「默認」值:
return rescue(function () {
return $this->method();
}, false);
return rescue(function () {
return $this->method();
}, function () {
return $this->failure();
});
<a name="method-resolve"></a>
#### `resolve()` {#collection-method}
`resolve` 函數使用 [服務容器](/docs/{{version}}/container) 解析給定名稱的類或接口的實例:
$api = resolve('HelpSpot\API');
<a name="method-response"></a>
#### `response()` {#collection-method}
`response` 函數創建 [響應](/docs/{{version}}/responses) 實例,或者獲得響應工廠的實例:
return response('Hello World', 200, $headers);
return response()->json(['foo' => 'bar'], 200, $headers);
<a name="method-retry"></a>
#### `retry()` {#collection-method}
`retry` 函數嘗試執行給定的回調,直到達到給定的最大嘗試閾值。如果回調沒有拋出異常,回調返回值將被返回。如果回調拋出異常,將自動重試。達到最大嘗試次數,將拋出異常:
return retry(5, function () {
// Attempt 5 times while resting 100ms in between attempts...
}, 100);
<a name="method-session"></a>
#### `session()` {#collection-method}
`session` 函數用于獲取或設置 [session](/docs/{{version}}/session) 值:
$value = session('key');
可以向該函數傳遞鍵值對數組來設置 session 值:
session(['chairs' => 7, 'instruments' => 3]);
不帶參數調用此函數,則返回存儲在 session 中的值:
$value = session()->get('key');
session()->put('key', $value);
<a name="method-tap"></a>
#### `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,
]);
<a name="method-today"></a>
#### `today()` {#collection-method}
`today` 函數根據當前日期創建新的 `Illuminate\Support\Carbon` 實例:
$today = today();
<a name="method-throw-if"></a>
#### `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'
);
<a name="method-throw-unless"></a>
#### `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'
);
<a name="method-trait-uses-recursive"></a>
#### `trait_uses_recursive()` {#collection-method}
`trait_uses_recursive` 返回被 trait 使用的全部 trait:
$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);
<a name="method-transform"></a>
#### `transform()` {#collection-method}
`transform` 函數執行基于(非 [空](#method-blank) )給定值的 `閉包`,并返回 `閉包` 的結果:
$callback = function ($value) {
return $value * 2;
};
$result = transform(5, $callback);
// 10
還可以傳遞一個默認值或 `閉包` 作為該函數的第三個參數。如果給定的值為空時,返回該值:
$result = transform(null, $callback, 'The value is blank');
// The value is blank
<a name="method-validator"></a>
#### `validator()` {#collection-method}
`validator` 函數根據指定的參數創建一個新的 [驗證器](/docs/{{version}}/validation) 實例。方便起見可以用它來代替 `Validator` facade:
$validator = validator($data, $rules, $messages);
<a name="method-value"></a>
#### `value()` {#collection-method}
`value` 函數返回給定值。如果傳遞 `閉包` 給此函數,將執行 `閉包` 并返回閉包調用的結果:
$result = value(true);
// true
$result = value(function () {
return false;
});
// false
<a name="method-view"></a>
#### `view()` {#collection-method}
`view` 函數獲取一個 [view](/docs/{{version}}/views) 實例:
return view('auth.login');
<a name="method-with"></a>
#### `with()` {#collection-method}
`with` 函數返回給定的值。如果傳遞了一個 `Closure` 給第二個參數,那么會返回 `Closure` 執行的結果:
$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
- 入門指南
- 安裝
- 部署
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- URL
- Session
- 表單驗證
- 錯誤
- 日志
- 前端開發
- Blade 模板
- 本地化
- 腳手架
- 編譯資源 Mix
- 安全相關
- 用戶認證
- API 認證
- 綜合話題
- 命令行
- 廣播
- 緩存
- 集合
- 事件
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 速查表
- Artisan
- Auth
- Blade
- Cache
- Collection
- Composer
- Config
- Container
- Cookie
- DB
- Environment
- Event
- File
- Helper
- Input
- Lang
- Log
- Model
- Pagination
- Queue
- Redirect
- Request
- Response
- Route
- SSH
- Schema
- Security
- Session
- Storage
- String
- URL
- UnitTest
- Validation
- View