輔助函式

簡介

Laravel 提供了多種全域 PHP「輔助函式」。這些函式中,大部分都是 Laravel 本身有在使用的。不過,若你覺得這些方法很方便的話,也可以在你自己的專案內使用。

可用的方法

陣列與物件

路徑

字串

Fluent 字串

URL

其他

方法清單

陣列與物件

Arr::accessible()

Arr::accessible 方法判斷給定的值是否能以陣列方式存取:

1use Illuminate\Support\Arr;
2use Illuminate\Support\Collection;
3 
4$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);
5 
6// true
7 
8$isAccessible = Arr::accessible(new Collection);
9 
10// true
11 
12$isAccessible = Arr::accessible('abc');
13 
14// false
15 
16$isAccessible = Arr::accessible(new stdClass);
17 
18// false
1use Illuminate\Support\Arr;
2use Illuminate\Support\Collection;
3 
4$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);
5 
6// true
7 
8$isAccessible = Arr::accessible(new Collection);
9 
10// true
11 
12$isAccessible = Arr::accessible('abc');
13 
14// false
15 
16$isAccessible = Arr::accessible(new stdClass);
17 
18// false

Arr::add()

Arr::add 方法會在給定的索引鍵 / 值配對不存在於給定陣列、或是該索引鍵的值 null 時將該配對新增到陣列上:

1use Illuminate\Support\Arr;
2 
3$array = Arr::add(['name' => 'Desk'], 'price', 100);
4 
5// ['name' => 'Desk', 'price' => 100]
6 
7$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);
8 
9// ['name' => 'Desk', 'price' => 100]
1use Illuminate\Support\Arr;
2 
3$array = Arr::add(['name' => 'Desk'], 'price', 100);
4 
5// ['name' => 'Desk', 'price' => 100]
6 
7$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);
8 
9// ['name' => 'Desk', 'price' => 100]

Arr::collapse()

Arr::collapse 方法將一組陣列的陣列坍縮(Collapse)成單一陣列:

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

Arr::crossJoin()

Arr::crossJoin 方法交叉合併(Cross Join)給定的陣列,產生一個包含所有可能排列(Permutation)笛卡兒積(Cartesian Product)

1use Illuminate\Support\Arr;
2 
3$matrix = Arr::crossJoin([1, 2], ['a', 'b']);
4 
5/*
6 [
7 [1, 'a'],
8 [1, 'b'],
9 [2, 'a'],
10 [2, 'b'],
11 ]
12*/
13 
14$matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']);
15 
16/*
17 [
18 [1, 'a', 'I'],
19 [1, 'a', 'II'],
20 [1, 'b', 'I'],
21 [1, 'b', 'II'],
22 [2, 'a', 'I'],
23 [2, 'a', 'II'],
24 [2, 'b', 'I'],
25 [2, 'b', 'II'],
26 ]
27*/
1use Illuminate\Support\Arr;
2 
3$matrix = Arr::crossJoin([1, 2], ['a', 'b']);
4 
5/*
6 [
7 [1, 'a'],
8 [1, 'b'],
9 [2, 'a'],
10 [2, 'b'],
11 ]
12*/
13 
14$matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']);
15 
16/*
17 [
18 [1, 'a', 'I'],
19 [1, 'a', 'II'],
20 [1, 'b', 'I'],
21 [1, 'b', 'II'],
22 [2, 'a', 'I'],
23 [2, 'a', 'II'],
24 [2, 'b', 'I'],
25 [2, 'b', 'II'],
26 ]
27*/

Arr::divide()

Arr::divide 方法回傳兩個陣列:一個陣列包含給定陣列的索引鍵,而另一個陣列則包含給定陣列的值:

1use Illuminate\Support\Arr;
2 
3[$keys, $values] = Arr::divide(['name' => 'Desk']);
4 
5// $keys: ['name']
6 
7// $values: ['Desk']
1use Illuminate\Support\Arr;
2 
3[$keys, $values] = Arr::divide(['name' => 'Desk']);
4 
5// $keys: ['name']
6 
7// $values: ['Desk']

Arr::dot()

Arr::dot 方法將多為陣列扁平化(Flatten)為一個使用「點 (.)」標記法來表示深度的一維陣列:

1use Illuminate\Support\Arr;
2 
3$array = ['products' => ['desk' => ['price' => 100]]];
4 
5$flattened = Arr::dot($array);
6 
7// ['products.desk.price' => 100]
1use Illuminate\Support\Arr;
2 
3$array = ['products' => ['desk' => ['price' => 100]]];
4 
5$flattened = Arr::dot($array);
6 
7// ['products.desk.price' => 100]

Arr::except()

Arr::except 方法從陣列中移除給定的索引鍵 / 值配對:

1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'Desk', 'price' => 100];
4 
5$filtered = Arr::except($array, ['price']);
6 
7// ['name' => 'Desk']
1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'Desk', 'price' => 100];
4 
5$filtered = Arr::except($array, ['price']);
6 
7// ['name' => 'Desk']

Arr::exists()

Arr::exists 方法會檢查給定的索引鍵是否存在於提供的陣列中:

1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'John Doe', 'age' => 17];
4 
5$exists = Arr::exists($array, 'name');
6 
7// true
8 
9$exists = Arr::exists($array, 'salary');
10 
11// false
1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'John Doe', 'age' => 17];
4 
5$exists = Arr::exists($array, 'name');
6 
7// true
8 
9$exists = Arr::exists($array, 'salary');
10 
11// false

Arr::first()

Arr::first 方法會回傳該陣列中通過給定布林測試的第一個元素:

1use Illuminate\Support\Arr;
2 
3$array = [100, 200, 300];
4 
5$first = Arr::first($array, function (int $value, int $key) {
6 return $value >= 150;
7});
8 
9// 200
1use Illuminate\Support\Arr;
2 
3$array = [100, 200, 300];
4 
5$first = Arr::first($array, function (int $value, int $key) {
6 return $value >= 150;
7});
8 
9// 200

也可以在第三個引數上提供一個預設值給該方法。若沒有任何值通過條件測試,就會回傳這個預設值:

1use Illuminate\Support\Arr;
2 
3$first = Arr::first($array, $callback, $default);
1use Illuminate\Support\Arr;
2 
3$first = Arr::first($array, $callback, $default);

Arr::flatten()

Arr::flatten 方法會將一個多維陣列扁平化(Flatten)為單一維度:

1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
4 
5$flattened = Arr::flatten($array);
6 
7// ['Joe', 'PHP', 'Ruby']
1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
4 
5$flattened = Arr::flatten($array);
6 
7// ['Joe', 'PHP', 'Ruby']

Arr::forget()

Arr::forget 方法使用「點 (.)」標記法來在多層巢狀陣列中移除給定的索引鍵 / 值配對:

1use Illuminate\Support\Arr;
2 
3$array = ['products' => ['desk' => ['price' => 100]]];
4 
5Arr::forget($array, 'products.desk');
6 
7// ['products' => []]
1use Illuminate\Support\Arr;
2 
3$array = ['products' => ['desk' => ['price' => 100]]];
4 
5Arr::forget($array, 'products.desk');
6 
7// ['products' => []]

Arr::get()

Arr::get 方法使用「點 (.)」標記法來在多層巢狀陣列中取值:

1use Illuminate\Support\Arr;
2 
3$array = ['products' => ['desk' => ['price' => 100]]];
4 
5$price = Arr::get($array, 'products.desk.price');
6 
7// 100
1use Illuminate\Support\Arr;
2 
3$array = ['products' => ['desk' => ['price' => 100]]];
4 
5$price = Arr::get($array, 'products.desk.price');
6 
7// 100

Arr::get 還接受一個預設值。若指定的索引鍵不存在時會回傳該預設值:

1use Illuminate\Support\Arr;
2 
3$discount = Arr::get($array, 'products.desk.discount', 0);
4 
5// 0
1use Illuminate\Support\Arr;
2 
3$discount = Arr::get($array, 'products.desk.discount', 0);
4 
5// 0

Arr::has()

Arr::has 方法使用「點 (.)」標記法來檢查給定的一個或多個項目是否存在:

1use Illuminate\Support\Arr;
2 
3$array = ['product' => ['name' => 'Desk', 'price' => 100]];
4 
5$contains = Arr::has($array, 'product.name');
6 
7// true
8 
9$contains = Arr::has($array, ['product.price', 'product.discount']);
10 
11// false
1use Illuminate\Support\Arr;
2 
3$array = ['product' => ['name' => 'Desk', 'price' => 100]];
4 
5$contains = Arr::has($array, 'product.name');
6 
7// true
8 
9$contains = Arr::has($array, ['product.price', 'product.discount']);
10 
11// false

Arr::hasAny()

Arr::hasAny 方法使用「點 (.)」標記法來檢查給定的多個項目中是否只少有一個存在:

1use Illuminate\Support\Arr;
2 
3$array = ['product' => ['name' => 'Desk', 'price' => 100]];
4 
5$contains = Arr::hasAny($array, 'product.name');
6 
7// true
8 
9$contains = Arr::hasAny($array, ['product.name', 'product.discount']);
10 
11// true
12 
13$contains = Arr::hasAny($array, ['category', 'product.discount']);
14 
15// false
1use Illuminate\Support\Arr;
2 
3$array = ['product' => ['name' => 'Desk', 'price' => 100]];
4 
5$contains = Arr::hasAny($array, 'product.name');
6 
7// true
8 
9$contains = Arr::hasAny($array, ['product.name', 'product.discount']);
10 
11// true
12 
13$contains = Arr::hasAny($array, ['category', 'product.discount']);
14 
15// false

Arr::isAssoc()

若給定的陣列為關聯式陣列(Associative Array)Arr::isAssoc 方法會回傳 true。當某個陣列的索引鍵不是以 0 開始依序排列的數字時,就是「關聯式」的陣列:

1use Illuminate\Support\Arr;
2 
3$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
4 
5// true
6 
7$isAssoc = Arr::isAssoc([1, 2, 3]);
8 
9// false
1use Illuminate\Support\Arr;
2 
3$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
4 
5// true
6 
7$isAssoc = Arr::isAssoc([1, 2, 3]);
8 
9// false

Arr::isList()

若給定陣列的索引鍵是從 0 開始的有序整數的話,Arr::isList 方法會回傳 true

1use Illuminate\Support\Arr;
2 
3$isList = Arr::isList(['foo', 'bar', 'baz']);
4 
5// true
6 
7$isList = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]);
8 
9// false
1use Illuminate\Support\Arr;
2 
3$isList = Arr::isList(['foo', 'bar', 'baz']);
4 
5// true
6 
7$isList = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]);
8 
9// false

Arr::join()

Arr::join 方法可使用字串來將各個陣列元素串接在一起。也可以用該方法的第二個引數來指定用於串接陣列中最後一個元素的字串:

1use Illuminate\Support\Arr;
2 
3$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];
4 
5$joined = Arr::join($array, ', ');
6 
7// Tailwind, Alpine, Laravel, Livewire
8 
9$joined = Arr::join($array, ', ', ' and ');
10 
11// Tailwind, Alpine, Laravel and Livewire
1use Illuminate\Support\Arr;
2 
3$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];
4 
5$joined = Arr::join($array, ', ');
6 
7// Tailwind, Alpine, Laravel, Livewire
8 
9$joined = Arr::join($array, ', ', ' and ');
10 
11// Tailwind, Alpine, Laravel and Livewire

Arr::keyBy()

Arr::keyBy 方法依照給定的索引鍵來為該陣列加上索引鍵。若多個項目有相同的索引鍵,則新的陣列中只會包含最後一個項目:

1use Illuminate\Support\Arr;
2 
3$array = [
4 ['product_id' => 'prod-100', 'name' => 'Desk'],
5 ['product_id' => 'prod-200', 'name' => 'Chair'],
6];
7 
8$keyed = Arr::keyBy($array, 'product_id');
9 
10/*
11 [
12 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
13 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
14 ]
15*/
1use Illuminate\Support\Arr;
2 
3$array = [
4 ['product_id' => 'prod-100', 'name' => 'Desk'],
5 ['product_id' => 'prod-200', 'name' => 'Chair'],
6];
7 
8$keyed = Arr::keyBy($array, 'product_id');
9 
10/*
11 [
12 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
13 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
14 ]
15*/

Arr::last()

Arr::last 方法會回傳該陣列中通過給定布林測試的最後一個元素:

1use Illuminate\Support\Arr;
2 
3$array = [100, 200, 300, 110];
4 
5$last = Arr::last($array, function (int $value, int $key) {
6 return $value >= 150;
7});
8 
9// 300
1use Illuminate\Support\Arr;
2 
3$array = [100, 200, 300, 110];
4 
5$last = Arr::last($array, function (int $value, int $key) {
6 return $value >= 150;
7});
8 
9// 300

可以在第三個引數上提供一個預設值給該方法。若沒有任何值通過條件測試,就會回傳這個預設值:

1use Illuminate\Support\Arr;
2 
3$last = Arr::last($array, $callback, $default);
1use Illuminate\Support\Arr;
2 
3$last = Arr::last($array, $callback, $default);

Arr::map()

Arr::map 可用於迭代整個陣列,並將各個陣列值與索引鍵傳入給定的回呼中。陣列值會被回呼中回傳的值給取代:

1use Illuminate\Support\Arr;
2 
3$array = ['first' => 'james', 'last' => 'kirk'];
4 
5$mapped = Arr::map($array, function (string $value, string $key) {
6 return ucfirst($value);
7});
8 
9// ['first' => 'James', 'last' => 'Kirk']
1use Illuminate\Support\Arr;
2 
3$array = ['first' => 'james', 'last' => 'kirk'];
4 
5$mapped = Arr::map($array, function (string $value, string $key) {
6 return ucfirst($value);
7});
8 
9// ['first' => 'James', 'last' => 'Kirk']

Arr::only()

Arr::only 方法回傳給定陣列中特定的索引鍵 / 值配對:

1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
4 
5$slice = Arr::only($array, ['name', 'price']);
6 
7// ['name' => 'Desk', 'price' => 100]
1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
4 
5$slice = Arr::only($array, ['name', 'price']);
6 
7// ['name' => 'Desk', 'price' => 100]

Arr::pluck()

Arr::pluck 方法可從給定陣列中取得給定索引鍵內的所有值:

1use Illuminate\Support\Arr;
2 
3$array = [
4 ['developer' => ['id' => 1, 'name' => 'Taylor']],
5 ['developer' => ['id' => 2, 'name' => 'Abigail']],
6];
7 
8$names = Arr::pluck($array, 'developer.name');
9 
10// ['Taylor', 'Abigail']
1use Illuminate\Support\Arr;
2 
3$array = [
4 ['developer' => ['id' => 1, 'name' => 'Taylor']],
5 ['developer' => ['id' => 2, 'name' => 'Abigail']],
6];
7 
8$names = Arr::pluck($array, 'developer.name');
9 
10// ['Taylor', 'Abigail']

也可以指定產生的清單要如何設定索引鍵:

1use Illuminate\Support\Arr;
2 
3$names = Arr::pluck($array, 'developer.name', 'developer.id');
4 
5// [1 => 'Taylor', 2 => 'Abigail']
1use Illuminate\Support\Arr;
2 
3$names = Arr::pluck($array, 'developer.name', 'developer.id');
4 
5// [1 => 'Taylor', 2 => 'Abigail']

Arr::prepend()

Arr::prepend 方法會將某個項目放到該陣列的最前面:

1use Illuminate\Support\Arr;
2 
3$array = ['one', 'two', 'three', 'four'];
4 
5$array = Arr::prepend($array, 'zero');
6 
7// ['zero', 'one', 'two', 'three', 'four']
1use Illuminate\Support\Arr;
2 
3$array = ['one', 'two', 'three', 'four'];
4 
5$array = Arr::prepend($array, 'zero');
6 
7// ['zero', 'one', 'two', 'three', 'four']

若有需要,也可以指定該值要使用的索引鍵:

1use Illuminate\Support\Arr;
2 
3$array = ['price' => 100];
4 
5$array = Arr::prepend($array, 'Desk', 'name');
6 
7// ['name' => 'Desk', 'price' => 100]
1use Illuminate\Support\Arr;
2 
3$array = ['price' => 100];
4 
5$array = Arr::prepend($array, 'Desk', 'name');
6 
7// ['name' => 'Desk', 'price' => 100]

Arr::prependKeysWith()

Arr::prependKeysWith 會將關聯式陣列中,將所有的索引鍵名稱加上給定的前置詞:

1use Illuminate\Support\Arr;
2 
3$array = [
4 'name' => 'Desk',
5 'price' => 100,
6];
7 
8$keyed = Arr::prependKeysWith($array, 'product.');
9 
10/*
11 [
12 'product.name' => 'Desk',
13 'product.price' => 100,
14 ]
15*/
1use Illuminate\Support\Arr;
2 
3$array = [
4 'name' => 'Desk',
5 'price' => 100,
6];
7 
8$keyed = Arr::prependKeysWith($array, 'product.');
9 
10/*
11 [
12 'product.name' => 'Desk',
13 'product.price' => 100,
14 ]
15*/

Arr::pull()

Arr::pull 方法從陣列中移除一組索引鍵 / 值配對:

1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'Desk', 'price' => 100];
4 
5$name = Arr::pull($array, 'name');
6 
7// $name: Desk
8 
9// $array: ['price' => 100]
1use Illuminate\Support\Arr;
2 
3$array = ['name' => 'Desk', 'price' => 100];
4 
5$name = Arr::pull($array, 'name');
6 
7// $name: Desk
8 
9// $array: ['price' => 100]

可以在第三個引數上提供一個預設值給該方法。若指定的索引鍵不存在,就會回傳這個預設值:

1use Illuminate\Support\Arr;
2 
3$value = Arr::pull($array, $key, $default);
1use Illuminate\Support\Arr;
2 
3$value = Arr::pull($array, $key, $default);

Arr::query()

Arr::query 方法將該陣列轉換為查詢字串(Query String)

1use Illuminate\Support\Arr;
2 
3$array = [
4 'name' => 'Taylor',
5 'order' => [
6 'column' => 'created_at',
7 'direction' => 'desc'
8 ]
9];
10 
11Arr::query($array);
12 
13// name=Taylor&order[column]=created_at&order[direction]=desc
1use Illuminate\Support\Arr;
2 
3$array = [
4 'name' => 'Taylor',
5 'order' => [
6 'column' => 'created_at',
7 'direction' => 'desc'
8 ]
9];
10 
11Arr::query($array);
12 
13// name=Taylor&order[column]=created_at&order[direction]=desc

Arr::random()

Arr::random 方法從陣列中隨機回傳一個值:

1use Illuminate\Support\Arr;
2 
3$array = [1, 2, 3, 4, 5];
4 
5$random = Arr::random($array);
6 
7// 4 - (隨機取得)
1use Illuminate\Support\Arr;
2 
3$array = [1, 2, 3, 4, 5];
4 
5$random = Arr::random($array);
6 
7// 4 - (隨機取得)

也可以在第二個引數上指定要回傳項目的數量。請注意,若有提供第二個引數,就算只要求一個項目,還是會回傳一組陣列:

1use Illuminate\Support\Arr;
2 
3$items = Arr::random($array, 2);
4 
5// [2, 5] - (隨機取得)
1use Illuminate\Support\Arr;
2 
3$items = Arr::random($array, 2);
4 
5// [2, 5] - (隨機取得)

Arr::set()

Arr::set 方法可使用「點 (.)」標記法來在多層巢狀陣列中賦值:

1use Illuminate\Support\Arr;
2 
3$array = ['products' => ['desk' => ['price' => 100]]];
4 
5Arr::set($array, 'products.desk.price', 200);
6 
7// ['products' => ['desk' => ['price' => 200]]]
1use Illuminate\Support\Arr;
2 
3$array = ['products' => ['desk' => ['price' => 100]]];
4 
5Arr::set($array, 'products.desk.price', 200);
6 
7// ['products' => ['desk' => ['price' => 200]]]

Arr::shuffle()

Arr::shuffle 方法會隨機排序該陣列內的項目:

1use Illuminate\Support\Arr;
2 
3$array = Arr::shuffle([1, 2, 3, 4, 5]);
4 
5// [3, 2, 5, 1, 4] - (隨機產生)
1use Illuminate\Support\Arr;
2 
3$array = Arr::shuffle([1, 2, 3, 4, 5]);
4 
5// [3, 2, 5, 1, 4] - (隨機產生)

Arr::sort()

Arr::sort 方法以陣列內的值來排列陣列:

1use Illuminate\Support\Arr;
2 
3$array = ['Desk', 'Table', 'Chair'];
4 
5$sorted = Arr::sort($array);
6 
7// ['Chair', 'Desk', 'Table']
1use Illuminate\Support\Arr;
2 
3$array = ['Desk', 'Table', 'Chair'];
4 
5$sorted = Arr::sort($array);
6 
7// ['Chair', 'Desk', 'Table']

也可以使用給定閉包的執行結果來排序陣列:

1use Illuminate\Support\Arr;
2 
3$array = [
4 ['name' => 'Desk'],
5 ['name' => 'Table'],
6 ['name' => 'Chair'],
7];
8 
9$sorted = array_values(Arr::sort($array, function (array $value) {
10 return $value['name'];
11}));
12 
13/*
14 [
15 ['name' => 'Chair'],
16 ['name' => 'Desk'],
17 ['name' => 'Table'],
18 ]
19*/
1use Illuminate\Support\Arr;
2 
3$array = [
4 ['name' => 'Desk'],
5 ['name' => 'Table'],
6 ['name' => 'Chair'],
7];
8 
9$sorted = array_values(Arr::sort($array, function (array $value) {
10 return $value['name'];
11}));
12 
13/*
14 [
15 ['name' => 'Chair'],
16 ['name' => 'Desk'],
17 ['name' => 'Table'],
18 ]
19*/

Arr::sortDesc()

Arr::sortDesc 方法將陣列以其值來降冪排序:

1use Illuminate\Support\Arr;
2 
3$array = ['Desk', 'Table', 'Chair'];
4 
5$sorted = Arr::sortDesc($array);
6 
7// ['Table', 'Desk', 'Chair']
1use Illuminate\Support\Arr;
2 
3$array = ['Desk', 'Table', 'Chair'];
4 
5$sorted = Arr::sortDesc($array);
6 
7// ['Table', 'Desk', 'Chair']

也可以使用給定閉包的執行結果來排序陣列:

1use Illuminate\Support\Arr;
2 
3$array = [
4 ['name' => 'Desk'],
5 ['name' => 'Table'],
6 ['name' => 'Chair'],
7];
8 
9$sorted = array_values(Arr::sortDesc($array, function (array $value) {
10 return $value['name'];
11}));
12 
13/*
14 [
15 ['name' => 'Table'],
16 ['name' => 'Desk'],
17 ['name' => 'Chair'],
18 ]
19*/
1use Illuminate\Support\Arr;
2 
3$array = [
4 ['name' => 'Desk'],
5 ['name' => 'Table'],
6 ['name' => 'Chair'],
7];
8 
9$sorted = array_values(Arr::sortDesc($array, function (array $value) {
10 return $value['name'];
11}));
12 
13/*
14 [
15 ['name' => 'Table'],
16 ['name' => 'Desk'],
17 ['name' => 'Chair'],
18 ]
19*/

Arr::sortRecursive()

Arr::sortRecursive 方法會遞迴排序陣列。當遇到數字索引鍵的子陣列時,會使用 sort 函式;若子陣列為關聯式陣列,則使用 ksort 函式:

1use Illuminate\Support\Arr;
2 
3$array = [
4 ['Roman', 'Taylor', 'Li'],
5 ['PHP', 'Ruby', 'JavaScript'],
6 ['one' => 1, 'two' => 2, 'three' => 3],
7];
8 
9$sorted = Arr::sortRecursive($array);
10 
11/*
12 [
13 ['JavaScript', 'PHP', 'Ruby'],
14 ['one' => 1, 'three' => 3, 'two' => 2],
15 ['Li', 'Roman', 'Taylor'],
16 ]
17*/
1use Illuminate\Support\Arr;
2 
3$array = [
4 ['Roman', 'Taylor', 'Li'],
5 ['PHP', 'Ruby', 'JavaScript'],
6 ['one' => 1, 'two' => 2, 'three' => 3],
7];
8 
9$sorted = Arr::sortRecursive($array);
10 
11/*
12 [
13 ['JavaScript', 'PHP', 'Ruby'],
14 ['one' => 1, 'three' => 3, 'two' => 2],
15 ['Li', 'Roman', 'Taylor'],
16 ]
17*/

Arr::toCssClasses()

Arr::toCssClasses 可以有條件地編譯 CSS class 字串。該方法接受一組包含 class 的陣列,其中,陣列的索引鍵代表欲新增的 class,陣列值則是一個布林運算式。若陣列的元素有數字索引鍵,則該元素一定會被加到轉譯後的 Class 列表上:

1use Illuminate\Support\Arr;
2 
3$isActive = false;
4$hasError = true;
5 
6$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError];
7 
8$classes = Arr::toCssClasses($array);
9 
10/*
11 'p-4 bg-red'
12*/
1use Illuminate\Support\Arr;
2 
3$isActive = false;
4$hasError = true;
5 
6$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError];
7 
8$classes = Arr::toCssClasses($array);
9 
10/*
11 'p-4 bg-red'
12*/

該方法用於提供了 Laravel 的「將 Class 於 Blade 元件的 Attribute Bag 合併」功能,以及 @class Blade 指示詞

Arr::undot()

Arr::undot 方法將一組使用「點 (.)」標記法的一維陣列展開為多維陣列:

1use Illuminate\Support\Arr;
2 
3$array = [
4 'user.name' => 'Kevin Malone',
5 'user.occupation' => 'Accountant',
6];
7 
8$array = Arr::undot($array);
9 
10// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]
1use Illuminate\Support\Arr;
2 
3$array = [
4 'user.name' => 'Kevin Malone',
5 'user.occupation' => 'Accountant',
6];
7 
8$array = Arr::undot($array);
9 
10// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]

Arr::where()

Arr::where 方法使用給定的閉包來篩選陣列:

1use Illuminate\Support\Arr;
2 
3$array = [100, '200', 300, '400', 500];
4 
5$filtered = Arr::where($array, function (string|int $value, int $key) {
6 return is_string($value);
7});
8 
9// [1 => '200', 3 => '400']
1use Illuminate\Support\Arr;
2 
3$array = [100, '200', 300, '400', 500];
4 
5$filtered = Arr::where($array, function (string|int $value, int $key) {
6 return is_string($value);
7});
8 
9// [1 => '200', 3 => '400']

Arr::whereNotNull()

Arr::whereNotNull 方法從給定陣列中移除所有 null 的值:

1use Illuminate\Support\Arr;
2 
3$array = [0, null];
4 
5$filtered = Arr::whereNotNull($array);
6 
7// [0 => 0]
1use Illuminate\Support\Arr;
2 
3$array = [0, null];
4 
5$filtered = Arr::whereNotNull($array);
6 
7// [0 => 0]

Arr::wrap()

Arr::wrap 將給定值包裝(Wrap)為陣列。若給定的值已為陣列,則該方法會直接回傳該陣列,不做其他修改:

1use Illuminate\Support\Arr;
2 
3$string = 'Laravel';
4 
5$array = Arr::wrap($string);
6 
7// ['Laravel']
1use Illuminate\Support\Arr;
2 
3$string = 'Laravel';
4 
5$array = Arr::wrap($string);
6 
7// ['Laravel']

若給定值為 null,則會回傳空陣列:

1use Illuminate\Support\Arr;
2 
3$array = Arr::wrap(null);
4 
5// []
1use Illuminate\Support\Arr;
2 
3$array = Arr::wrap(null);
4 
5// []

data_fill()

data_fill 方法使用「點 (.)」標記法來在巢狀陣列或物件中填上原本不存在的值:

1$data = ['products' => ['desk' => ['price' => 100]]];
2 
3data_fill($data, 'products.desk.price', 200);
4 
5// ['products' => ['desk' => ['price' => 100]]]
6 
7data_fill($data, 'products.desk.discount', 10);
8 
9// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]
1$data = ['products' => ['desk' => ['price' => 100]]];
2 
3data_fill($data, 'products.desk.price', 200);
4 
5// ['products' => ['desk' => ['price' => 100]]]
6 
7data_fill($data, 'products.desk.discount', 10);
8 
9// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]

該方法也支援使用星號作為萬用字元,會填上對應的目標:

1$data = [
2 'products' => [
3 ['name' => 'Desk 1', 'price' => 100],
4 ['name' => 'Desk 2'],
5 ],
6];
7 
8data_fill($data, 'products.*.price', 200);
9 
10/*
11 [
12 'products' => [
13 ['name' => 'Desk 1', 'price' => 100],
14 ['name' => 'Desk 2', 'price' => 200],
15 ],
16 ]
17*/
1$data = [
2 'products' => [
3 ['name' => 'Desk 1', 'price' => 100],
4 ['name' => 'Desk 2'],
5 ],
6];
7 
8data_fill($data, 'products.*.price', 200);
9 
10/*
11 [
12 'products' => [
13 ['name' => 'Desk 1', 'price' => 100],
14 ['name' => 'Desk 2', 'price' => 200],
15 ],
16 ]
17*/

data_get()

data_get 方法使用「點 (.)」標記法來從巢狀陣列或物件中取值:

1$data = ['products' => ['desk' => ['price' => 100]]];
2 
3$price = data_get($data, 'products.desk.price');
4 
5// 100
1$data = ['products' => ['desk' => ['price' => 100]]];
2 
3$price = data_get($data, 'products.desk.price');
4 
5// 100

data_get 還接受一個預設值。若找不到指定的索引鍵時會回傳該預設值:

1$discount = data_get($data, 'products.desk.discount', 0);
2 
3// 0
1$discount = data_get($data, 'products.desk.discount', 0);
2 
3// 0

該方法也接受使用星號來作為萬用字元,可以套用到陣列或物件上的任何索引鍵:

1$data = [
2 'product-one' => ['name' => 'Desk 1', 'price' => 100],
3 'product-two' => ['name' => 'Desk 2', 'price' => 150],
4];
5 
6data_get($data, '*.name');
7 
8// ['Desk 1', 'Desk 2'];
1$data = [
2 'product-one' => ['name' => 'Desk 1', 'price' => 100],
3 'product-two' => ['name' => 'Desk 2', 'price' => 150],
4];
5 
6data_get($data, '*.name');
7 
8// ['Desk 1', 'Desk 2'];

data_set()

data_set 函式使用「點 (.)」標記法來在巢狀陣列或物件上賦值:

1$data = ['products' => ['desk' => ['price' => 100]]];
2 
3data_set($data, 'products.desk.price', 200);
4 
5// ['products' => ['desk' => ['price' => 200]]]
1$data = ['products' => ['desk' => ['price' => 100]]];
2 
3data_set($data, 'products.desk.price', 200);
4 
5// ['products' => ['desk' => ['price' => 200]]]

該函式也接受使用星號作為萬用字元,會為設定相應的目標賦值:

1$data = [
2 'products' => [
3 ['name' => 'Desk 1', 'price' => 100],
4 ['name' => 'Desk 2', 'price' => 150],
5 ],
6];
7 
8data_set($data, 'products.*.price', 200);
9 
10/*
11 [
12 'products' => [
13 ['name' => 'Desk 1', 'price' => 200],
14 ['name' => 'Desk 2', 'price' => 200],
15 ],
16 ]
17*/
1$data = [
2 'products' => [
3 ['name' => 'Desk 1', 'price' => 100],
4 ['name' => 'Desk 2', 'price' => 150],
5 ],
6];
7 
8data_set($data, 'products.*.price', 200);
9 
10/*
11 [
12 'products' => [
13 ['name' => 'Desk 1', 'price' => 200],
14 ['name' => 'Desk 2', 'price' => 200],
15 ],
16 ]
17*/

預設情況下,會複寫現有的值。若只想為不存在的項目賦值,可傳入 false 作為第四個引數給該函式:

1$data = ['products' => ['desk' => ['price' => 100]]];
2 
3data_set($data, 'products.desk.price', 200, overwrite: false);
4 
5// ['products' => ['desk' => ['price' => 100]]]
1$data = ['products' => ['desk' => ['price' => 100]]];
2 
3data_set($data, 'products.desk.price', 200, overwrite: false);
4 
5// ['products' => ['desk' => ['price' => 100]]]

head()

head 方法回傳給定陣列中的第一個元素:

1$array = [100, 200, 300];
2 
3$first = head($array);
4 
5// 100
1$array = [100, 200, 300];
2 
3$first = head($array);
4 
5// 100

last()

last 方法回傳給定陣列中的最後一個元素:

1$array = [100, 200, 300];
2 
3$last = last($array);
4 
5// 300
1$array = [100, 200, 300];
2 
3$last = last($array);
4 
5// 300

路徑

app_path()

app_path 回傳專案 app 目錄的完整名稱路徑。也可以使用 app_path 函式來為 app 目錄下相對路徑的完整名稱路徑:

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

base_path()

base_path 函式回傳專案根目錄的完整名稱路徑。也可以使用 base_path 來產生相對於根目錄下給定檔案的完整名稱路徑:

1$path = base_path();
2 
3$path = base_path('vendor/bin');
1$path = base_path();
2 
3$path = base_path('vendor/bin');

config_path()

config_path 函式回傳專案 config 目錄的完整名稱路徑。也可以使用 config_path 函式來產生專案 config 目錄內給定檔案的完整名稱路徑:

1$path = config_path();
2 
3$path = config_path('app.php');
1$path = config_path();
2 
3$path = config_path('app.php');

database_path()

database_path 函式回傳專案 database 目錄的完整名稱路徑。也可以使用 database_path 函式來產生 database 目錄下給定檔案的完整名稱路徑:

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

lang_path()

lang_path 函式回傳專案 lang 目錄的完整名稱路徑。也可以使用 lang_path 函式來產生 lang 目錄下給定檔案的完整名稱路徑:

1$path = lang_path();
2 
3$path = lang_path('en/messages.php');
1$path = lang_path();
2 
3$path = lang_path('en/messages.php');
lightbulb

預設情況下,Laravel 專案的 Skeleton 中未包含 lang 目錄。若想自定 Laravel 的語系檔,可以使用 lang:publish Artisan 指令來安裝語系檔:

mix()

mix 函式回傳版本化的 Mix 檔案路徑:

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

public_path()

public_path 函式回傳專案 public 目錄的完整名稱路徑。也可以使用 public_path 函式來產生 public 目錄下給定檔案的完整名稱路徑:

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

resource_path()

resource_path 函式回傳專案 resources 目錄的完整名稱路徑。也可以使用 resource_path 函式來產生 resources 目錄下給定檔案的完整名稱路徑:

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

storage_path()

storage_path 函式回傳專案 storage 目錄的完整名稱路徑。也可以使用 storage_path 函式來產生 storage 目錄下給定檔案的完整名稱路徑:

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

字串

__()

__ 函式使用語系檔來翻譯給定的翻譯字串或翻譯索引鍵:

1echo __('Welcome to our application');
2 
3echo __('messages.welcome');
1echo __('Welcome to our application');
2 
3echo __('messages.welcome');

若指定的翻譯字串或翻譯索引鍵不存在時,__ 函式會回傳給定的值。因此,在上述範例中,若 messages.welcome 索引鍵不存在,__ 函式會回傳 messages.welcome

class_basename()

class_basename 函式回傳給定類別在移除類別 Namespace 後的類別名稱:

1$class = class_basename('Foo\Bar\Baz');
2 
3// Baz
1$class = class_basename('Foo\Bar\Baz');
2 
3// Baz

e()

e 函式執行 PHP 的 htmlspecialchars 函式,其中 double_encode 選項預設為 true

1echo e('<html>foo</html>');
2 
3// &lt;html&gt;foo&lt;/html&gt;
1echo e('<html>foo</html>');
2 
3// &lt;html&gt;foo&lt;/html&gt;

preg_replace_array()

preg_replace_array 函式使用陣列來依序在陣列中取代給定的格式:

1$string = 'The event will take place between :start and :end';
2 
3$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);
4 
5// The event will take place between 8:30 and 9:00
1$string = 'The event will take place between :start and :end';
2 
3$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);
4 
5// The event will take place between 8:30 and 9:00

Str::after()

Str::after 方法回傳字串中給定值以後的所有內容。若該字串中找不到給定值,會回傳整個字串:

1use Illuminate\Support\Str;
2 
3$slice = Str::after('This is my name', 'This is');
4 
5// ' my name'
1use Illuminate\Support\Str;
2 
3$slice = Str::after('This is my name', 'This is');
4 
5// ' my name'

Str::afterLast()

Str::afterLast 方法回傳給定字串後最後一個出現給定值之後的所有內容。若找不到該值,會回傳整個字串:

1use Illuminate\Support\Str;
2 
3$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');
4 
5// 'Controller'
1use Illuminate\Support\Str;
2 
3$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');
4 
5// 'Controller'

Str::ascii()

Str::ascii 方法會嘗試將給定字串翻譯為 ASCII 值:

1use Illuminate\Support\Str;
2 
3$slice = Str::ascii('û');
4 
5// 'u'
1use Illuminate\Support\Str;
2 
3$slice = Str::ascii('û');
4 
5// 'u'

Str::before()

Str::before 回傳字串在遇到給定值前的所有內容:

1use Illuminate\Support\Str;
2 
3$slice = Str::before('This is my name', 'my name');
4 
5// 'This is '
1use Illuminate\Support\Str;
2 
3$slice = Str::before('This is my name', 'my name');
4 
5// 'This is '

Str::beforeLast()

Str::beforeLast 方法回傳字串中最後一次出現給定值以前的所有內容:

1use Illuminate\Support\Str;
2 
3$slice = Str::beforeLast('This is my name', 'is');
4 
5// 'This '
1use Illuminate\Support\Str;
2 
3$slice = Str::beforeLast('This is my name', 'is');
4 
5// 'This '

Str::between()

Str::between 方法回傳介於兩個值之間的字串:

1use Illuminate\Support\Str;
2 
3$slice = Str::between('This is my name', 'This', 'name');
4 
5// ' is my '
1use Illuminate\Support\Str;
2 
3$slice = Str::between('This is my name', 'This', 'name');
4 
5// ' is my '

Str::betweenFirst()

Str::betweenFirst 方法回傳介於兩個值之間,最小的可能字串部分:

1use Illuminate\Support\Str;
2 
3$slice = Str::betweenFirst('[a] bc [d]', '[', ']');
4 
5// 'a'
1use Illuminate\Support\Str;
2 
3$slice = Str::betweenFirst('[a] bc [d]', '[', ']');
4 
5// 'a'

Str::camel()

Str::camel 方法將給定字串轉為 camelCase —— 駝峰命名法的大小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::camel('foo_bar');
4 
5// fooBar
1use Illuminate\Support\Str;
2 
3$converted = Str::camel('foo_bar');
4 
5// fooBar

Str::contains()

Str::contains 方法判斷給定字串是否包含給定值。該方法區分大小寫:

1use Illuminate\Support\Str;
2 
3$contains = Str::contains('This is my name', 'my');
4 
5// true
1use Illuminate\Support\Str;
2 
3$contains = Str::contains('This is my name', 'my');
4 
5// true

也可以傳入一組要判斷的陣列值,來判斷給定字串中是否有包含該陣列中任何一個值:

1use Illuminate\Support\Str;
2 
3$contains = Str::contains('This is my name', ['my', 'foo']);
4 
5// true
1use Illuminate\Support\Str;
2 
3$contains = Str::contains('This is my name', ['my', 'foo']);
4 
5// true

Str::containsAll()

Str::containsAll 判斷給定字串是否有包含給定陣列中的所有值:

1use Illuminate\Support\Str;
2 
3$containsAll = Str::containsAll('This is my name', ['my', 'name']);
4 
5// true
1use Illuminate\Support\Str;
2 
3$containsAll = Str::containsAll('This is my name', ['my', 'name']);
4 
5// true

Str::endsWith()

Str::endsWith` 方法可判斷給定字串是否以給定值結尾:

1use Illuminate\Support\Str;
2 
3$result = Str::endsWith('This is my name', 'name');
4 
5// true
1use Illuminate\Support\Str;
2 
3$result = Str::endsWith('This is my name', 'name');
4 
5// true

也可以傳入一組陣列值來判斷給定字串的結尾是否符合該陣列內的其中一項:

1use Illuminate\Support\Str;
2 
3$result = Str::endsWith('This is my name', ['name', 'foo']);
4 
5// true
6 
7$result = Str::endsWith('This is my name', ['this', 'foo']);
8 
9// false
1use Illuminate\Support\Str;
2 
3$result = Str::endsWith('This is my name', ['name', 'foo']);
4 
5// true
6 
7$result = Str::endsWith('This is my name', ['this', 'foo']);
8 
9// false

Str::excerpt()

Str::excerpt 方法從給定字串中截取摘要,這個摘要符合該字串中第一個符合給定片語 (Phrase) 的實體:

1use Illuminate\Support\Str;
2 
3$excerpt = Str::excerpt('This is my name', 'my', [
4 'radius' => 3
5]);
6 
7// '...is my na...'
1use Illuminate\Support\Str;
2 
3$excerpt = Str::excerpt('This is my name', 'my', [
4 'radius' => 3
5]);
6 
7// '...is my na...'

radius 選項的預設值為 100。該選項可用來定義經過截取的字串中左右兩邊各需顯式多少個字元:

此外,也可使用 omission 選項來定義應被加到截取字串前後的字串:

1use Illuminate\Support\Str;
2 
3$excerpt = Str::excerpt('This is my name', 'name', [
4 'radius' => 3,
5 'omission' => '(...) '
6]);
7 
8// '(...) my name'
1use Illuminate\Support\Str;
2 
3$excerpt = Str::excerpt('This is my name', 'name', [
4 'radius' => 3,
5 'omission' => '(...) '
6]);
7 
8// '(...) my name'

Str::finish()

Str::finish 方法會在給定字串不是以給定值結尾時,在該字串後方加上這個值:

1use Illuminate\Support\Str;
2 
3$adjusted = Str::finish('this/string', '/');
4 
5// this/string/
6 
7$adjusted = Str::finish('this/string/', '/');
8 
9// this/string/
1use Illuminate\Support\Str;
2 
3$adjusted = Str::finish('this/string', '/');
4 
5// this/string/
6 
7$adjusted = Str::finish('this/string/', '/');
8 
9// this/string/

Str::headline()

Str::headline 方法將以大小寫、減號、底線等方式區隔的字串轉換為以空格區隔的字串,並將其中每個單詞的首字母都轉為大寫:

1use Illuminate\Support\Str;
2 
3$headline = Str::headline('steve_jobs');
4 
5// Steve Jobs
6 
7$headline = Str::headline('EmailNotificationSent');
8 
9// Email Notification Sent
1use Illuminate\Support\Str;
2 
3$headline = Str::headline('steve_jobs');
4 
5// Steve Jobs
6 
7$headline = Str::headline('EmailNotificationSent');
8 
9// Email Notification Sent

Str::inlineMarkdown()

Str::inlineMarkdown 方法使用 CommonMarkdown 來將 GitHub Flavored Markdown 轉換為內嵌的 HTML。不過,與 markdown 不同,該方法不會將所有產生的 HTML 以區塊層級的元素包裝起來。

1use Illuminate\Support\Str;
2 
3$html = Str::inlineMarkdown('**Laravel**');
4 
5// <strong>Laravel</strong>
1use Illuminate\Support\Str;
2 
3$html = Str::inlineMarkdown('**Laravel**');
4 
5// <strong>Laravel</strong>

Str::is()

Str::is 判斷給定字串是否符合給定的格式。可使用星號作為萬用字元:

1use Illuminate\Support\Str;
2 
3$matches = Str::is('foo*', 'foobar');
4 
5// true
6 
7$matches = Str::is('baz*', 'foobar');
8 
9// false
1use Illuminate\Support\Str;
2 
3$matches = Str::is('foo*', 'foobar');
4 
5// true
6 
7$matches = Str::is('baz*', 'foobar');
8 
9// false

Str::isAscii()

Str::isAscii 方法判斷給定字串是否為 7 位元 ASCII:

1use Illuminate\Support\Str;
2 
3$isAscii = Str::isAscii('Taylor');
4 
5// true
6 
7$isAscii = Str::isAscii('ü');
8 
9// false
1use Illuminate\Support\Str;
2 
3$isAscii = Str::isAscii('Taylor');
4 
5// true
6 
7$isAscii = Str::isAscii('ü');
8 
9// false

Str::isJson()

Str::isJson 方法會判斷給定字串是否為有效的 JSON:

1use Illuminate\Support\Str;
2 
3$result = Str::isJson('[1,2,3]');
4 
5// true
6 
7$result = Str::isJson('{"first": "John", "last": "Doe"}');
8 
9// true
10 
11$result = Str::isJson('{first: "John", last: "Doe"}');
12 
13// false
1use Illuminate\Support\Str;
2 
3$result = Str::isJson('[1,2,3]');
4 
5// true
6 
7$result = Str::isJson('{"first": "John", "last": "Doe"}');
8 
9// true
10 
11$result = Str::isJson('{first: "John", last: "Doe"}');
12 
13// false

Str::isUlid()

Str::isUlid 方法可判斷給定字串是否為有效的 ULID:

1use Illuminate\Support\Str;
2 
3$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');
4 
5// true
6 
7$isUlid = Str::isUlid('laravel');
8 
9// false
1use Illuminate\Support\Str;
2 
3$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');
4 
5// true
6 
7$isUlid = Str::isUlid('laravel');
8 
9// false

Str::isUuid()

Str::isUuid 方法判斷給定字串是否為有效的 UUID:

1use Illuminate\Support\Str;
2 
3$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');
4 
5// true
6 
7$isUuid = Str::isUuid('laravel');
8 
9// false
1use Illuminate\Support\Str;
2 
3$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');
4 
5// true
6 
7$isUuid = Str::isUuid('laravel');
8 
9// false

Str::kebab()

Str::kebab 方法將給定字串轉換為 kebab-case

1use Illuminate\Support\Str;
2 
3$converted = Str::kebab('fooBar');
4 
5// foo-bar
1use Illuminate\Support\Str;
2 
3$converted = Str::kebab('fooBar');
4 
5// foo-bar

Str::lcfirst()

Str::lcfirst 方法回傳給定字串第一個字元轉為小寫後的字串:

1use Illuminate\Support\Str;
2 
3$string = Str::lcfirst('Foo Bar');
4 
5// foo Bar
1use Illuminate\Support\Str;
2 
3$string = Str::lcfirst('Foo Bar');
4 
5// foo Bar

Str::length()

Str::length 方法回傳給定字串的長度:

1use Illuminate\Support\Str;
2 
3$length = Str::length('Laravel');
4 
5// 7
1use Illuminate\Support\Str;
2 
3$length = Str::length('Laravel');
4 
5// 7

Str::limit()

Str::limit 方法將給定字串截斷成指定長度:

1use Illuminate\Support\Str;
2 
3$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);
4 
5// The quick brown fox...
1use Illuminate\Support\Str;
2 
3$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);
4 
5// The quick brown fox...

也可以傳入第三個引數給該方法,以更改當字串被截斷時要加在最後方的內容:

1use Illuminate\Support\Str;
2 
3$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
4 
5// The quick brown fox (...)
1use Illuminate\Support\Str;
2 
3$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
4 
5// The quick brown fox (...)

Str::lower()

Str::lower 方法將給定字串轉為小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::lower('LARAVEL');
4 
5// laravel
1use Illuminate\Support\Str;
2 
3$converted = Str::lower('LARAVEL');
4 
5// laravel

Str::markdown()

Str::markdown 方法使用 CommonMark 來將 GitHub Flavored Markdown 轉換為 HTML:

1use Illuminate\Support\Str;
2 
3$html = Str::markdown('# Laravel');
4 
5// <h1>Laravel</h1>
6 
7$html = Str::markdown('# Taylor <b>Otwell</b>', [
8 'html_input' => 'strip',
9]);
10 
11// <h1>Taylor Otwell</h1>
1use Illuminate\Support\Str;
2 
3$html = Str::markdown('# Laravel');
4 
5// <h1>Laravel</h1>
6 
7$html = Str::markdown('# Taylor <b>Otwell</b>', [
8 'html_input' => 'strip',
9]);
10 
11// <h1>Taylor Otwell</h1>

Str::mask()

Str::mask 方法將字串中的一部分轉為重複字元,可用來為 E-Mail 位址或電話號碼⋯⋯等字串打碼(Obfuscate)

1use Illuminate\Support\Str;
2 
3$string = Str::mask('[email protected]', '*', 3);
4 
5// tay***************
1use Illuminate\Support\Str;
2 
3$string = Str::mask('[email protected]', '*', 3);
4 
5// tay***************

若有需要,mask 方法的第三個引數可提供負數,這樣 mask 就會從字串結尾起給定的長度開始打碼:

1$string = Str::mask('[email protected]', '*', -15, 3);
2 
3// tay***@example.com
1$string = Str::mask('[email protected]', '*', -15, 3);
2 
3// tay***@example.com

Str::orderedUuid()

Str::orderedUuid 方法會產生一個「時戳優先(Timestamp First)」的 UUID,可用來儲存在有所引的資料庫欄位中。使用本方法產生的 UUID 在排序時會被排到之前使用本方法產生的 UUID 之後:

1use Illuminate\Support\Str;
2 
3return (string) Str::orderedUuid();
1use Illuminate\Support\Str;
2 
3return (string) Str::orderedUuid();

Str::padBoth()

Str::padBoth 方法包裝了 PHP 的 str_path 方法,會填充字串的兩端,直到字串符合預期的長度:

1use Illuminate\Support\Str;
2 
3$padded = Str::padBoth('James', 10, '_');
4 
5// '__James___'
6 
7$padded = Str::padBoth('James', 10);
8 
9// ' James '
1use Illuminate\Support\Str;
2 
3$padded = Str::padBoth('James', 10, '_');
4 
5// '__James___'
6 
7$padded = Str::padBoth('James', 10);
8 
9// ' James '

Str::padLeft()

Str::padLeft 包裝了 PHP 的 str_pad 方法,會使用另一個字串填充給定字串的左邊,直到符合預期的長度:

1use Illuminate\Support\Str;
2 
3$padded = Str::padLeft('James', 10, '-=');
4 
5// '-=-=-James'
6 
7$padded = Str::padLeft('James', 10);
8 
9// ' James'
1use Illuminate\Support\Str;
2 
3$padded = Str::padLeft('James', 10, '-=');
4 
5// '-=-=-James'
6 
7$padded = Str::padLeft('James', 10);
8 
9// ' James'

Str::padRight()

Str::padRight 包裝了 PHP 的 str_pad 方法,會使用另一個字串填充給定字串的右邊,直到符合預期的長度:

1use Illuminate\Support\Str;
2 
3$padded = Str::padRight('James', 10, '-');
4 
5// 'James-----'
6 
7$padded = Str::padRight('James', 10);
8 
9// 'James '
1use Illuminate\Support\Str;
2 
3$padded = Str::padRight('James', 10, '-');
4 
5// 'James-----'
6 
7$padded = Str::padRight('James', 10);
8 
9// 'James '

Str::password()

Str::password 方法可用來產生指定長度的安全隨機密碼。產生的密碼會包含字母、數字、符號、與空格的組合。預設情況下,密碼為 32 個字元長:

1use Illuminate\Support\Str;
2 
3$password = Str::password();
4 
5// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4'
6 
7$password = Str::password(12);
8 
9// 'qwuar>#V|i]N'
1use Illuminate\Support\Str;
2 
3$password = Str::password();
4 
5// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4'
6 
7$password = Str::password(12);
8 
9// 'qwuar>#V|i]N'

Str::plural()

Str::plural 方法將單數單詞轉換為其複數形態。該方法支援所有 Laravel Pluralizer 所支援的語言

1use Illuminate\Support\Str;
2 
3$plural = Str::plural('car');
4 
5// cars
6 
7$plural = Str::plural('child');
8 
9// children
1use Illuminate\Support\Str;
2 
3$plural = Str::plural('car');
4 
5// cars
6 
7$plural = Str::plural('child');
8 
9// children

也可以提供一個整數作為該方法的第二個引數,用來判斷要取得該字串的單數或複數型:

1use Illuminate\Support\Str;
2 
3$plural = Str::plural('child', 2);
4 
5// children
6 
7$singular = Str::plural('child', 1);
8 
9// child
1use Illuminate\Support\Str;
2 
3$plural = Str::plural('child', 2);
4 
5// children
6 
7$singular = Str::plural('child', 1);
8 
9// child

Str::pluralStudly()

Str::plural 方法將單數單詞轉換為其複數形態,並以 Studly 命名法 (StudlyCase) 來格式化字串。該方法支援所有 Laravel Pluralizer 所支援的語言

1use Illuminate\Support\Str;
2 
3$plural = Str::pluralStudly('VerifiedHuman');
4 
5// VerifiedHumans
6 
7$plural = Str::pluralStudly('UserFeedback');
8 
9// UserFeedback
1use Illuminate\Support\Str;
2 
3$plural = Str::pluralStudly('VerifiedHuman');
4 
5// VerifiedHumans
6 
7$plural = Str::pluralStudly('UserFeedback');
8 
9// UserFeedback

也可以提供一個整數作為該方法的第二個引數,用來判斷要取得該字串的單數或複數型:

1use Illuminate\Support\Str;
2 
3$plural = Str::pluralStudly('VerifiedHuman', 2);
4 
5// VerifiedHumans
6 
7$singular = Str::pluralStudly('VerifiedHuman', 1);
8 
9// VerifiedHuman
1use Illuminate\Support\Str;
2 
3$plural = Str::pluralStudly('VerifiedHuman', 2);
4 
5// VerifiedHumans
6 
7$singular = Str::pluralStudly('VerifiedHuman', 1);
8 
9// VerifiedHuman

Str::random()

Str::random 方法產生指定長度的隨機字串。該函式使用 PHP 的 random_bytes 函式:

1use Illuminate\Support\Str;
2 
3$random = Str::random(40);
1use Illuminate\Support\Str;
2 
3$random = Str::random(40);

Str::remove()

Str::remove 方法從字串中移除給定的一個或多個值:

1use Illuminate\Support\Str;
2 
3$string = 'Peter Piper picked a peck of pickled peppers.';
4 
5$removed = Str::remove('e', $string);
6 
7// Ptr Pipr pickd a pck of pickld ppprs.
1use Illuminate\Support\Str;
2 
3$string = 'Peter Piper picked a peck of pickled peppers.';
4 
5$removed = Str::remove('e', $string);
6 
7// Ptr Pipr pickd a pck of pickld ppprs.

也可以傳入 false 作為第三個引數給 remove 方法來在移除字串時忽略大小寫差異:

Str::replace()

Str::replace 方法在字串中取代給定字串:

1use Illuminate\Support\Str;
2 
3$string = 'Laravel 10.x';
4 
5$replaced = Str::replace('10.x', '11.x', $string);
6 
7// Laravel 11.x
1use Illuminate\Support\Str;
2 
3$string = 'Laravel 10.x';
4 
5$replaced = Str::replace('10.x', '11.x', $string);
6 
7// Laravel 11.x

Str::replaceArray()

Str::replaceArray 函式使用陣列來依序在陣列中取代給定的值:

1use Illuminate\Support\Str;
2 
3$string = 'The event will take place between ? and ?';
4 
5$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);
6 
7// The event will take place between 8:30 and 9:00
1use Illuminate\Support\Str;
2 
3$string = 'The event will take place between ? and ?';
4 
5$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);
6 
7// The event will take place between 8:30 and 9:00

Str::replaceFirst()

Str::replaceFirst 方法取代字串中第一次出現的給定值:

1use Illuminate\Support\Str;
2 
3$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');
4 
5// a quick brown fox jumps over the lazy dog
1use Illuminate\Support\Str;
2 
3$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');
4 
5// a quick brown fox jumps over the lazy dog

Str::replaceLast()

Str::replaceLast 方法取代字串中最後一次出現的給定值:

1use Illuminate\Support\Str;
2 
3$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');
4 
5// the quick brown fox jumps over a lazy dog
1use Illuminate\Support\Str;
2 
3$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');
4 
5// the quick brown fox jumps over a lazy dog

Str::reverse()

Str::reverse 方法反轉給定的字串:

1use Illuminate\Support\Str;
2 
3$reversed = Str::reverse('Hello World');
4 
5// dlroW olleH
1use Illuminate\Support\Str;
2 
3$reversed = Str::reverse('Hello World');
4 
5// dlroW olleH

Str::singular()

Str::plural 方法將單詞轉換為其單數形態。該方法支援所有 Laravel Pluralizer 所支援的語言

1use Illuminate\Support\Str;
2 
3$singular = Str::singular('cars');
4 
5// car
6 
7$singular = Str::singular('children');
8 
9// child
1use Illuminate\Support\Str;
2 
3$singular = Str::singular('cars');
4 
5// car
6 
7$singular = Str::singular('children');
8 
9// child

Str::slug()

Str::slug 方法以給定字串產生適合在 URL 中使用的「Slug」格式:

1use Illuminate\Support\Str;
2 
3$slug = Str::slug('Laravel 5 Framework', '-');
4 
5// laravel-5-framework
1use Illuminate\Support\Str;
2 
3$slug = Str::slug('Laravel 5 Framework', '-');
4 
5// laravel-5-framework

Str::snake()

Str::snake 方法將給定字串轉為 snake_case —— 蛇型命名法的大小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::snake('fooBar');
4 
5// foo_bar
6 
7$converted = Str::snake('fooBar', '-');
8 
9// foo-bar
1use Illuminate\Support\Str;
2 
3$converted = Str::snake('fooBar');
4 
5// foo_bar
6 
7$converted = Str::snake('fooBar', '-');
8 
9// foo-bar

Str::squish()

Str::squish 方法會從字串內移除所有多餘的空格,其中亦包含單詞間多餘的空格:

1use Illuminate\Support\Str;
2 
3$string = Str::squish(' laravel framework ');
4 
5// laravel framework
1use Illuminate\Support\Str;
2 
3$string = Str::squish(' laravel framework ');
4 
5// laravel framework

Str::start()

Str::start 方法會在給定字串不是以給定值起始時,在該字串前方加上這個值:

1use Illuminate\Support\Str;
2 
3$adjusted = Str::start('this/string', '/');
4 
5// /this/string
6 
7$adjusted = Str::start('/this/string', '/');
8 
9// /this/string
1use Illuminate\Support\Str;
2 
3$adjusted = Str::start('this/string', '/');
4 
5// /this/string
6 
7$adjusted = Str::start('/this/string', '/');
8 
9// /this/string

Str::startsWith()

Str::startsWith` 方法可判斷給定字串是否以給定值起始:

1use Illuminate\Support\Str;
2 
3$result = Str::startsWith('This is my name', 'This');
4 
5// true
1use Illuminate\Support\Str;
2 
3$result = Str::startsWith('This is my name', 'This');
4 
5// true

若傳入一組陣列,當字串以給定值中任何一個值開頭時,startsWith 方法會回傳 true

1$result = Str::startsWith('This is my name', ['This', 'That', 'There']);
2 
3// true
1$result = Str::startsWith('This is my name', ['This', 'That', 'There']);
2 
3// true

Str::studly()

Str::studly 方法將給定字串轉為 StudlyCase —— Studly 命名法的大小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::studly('foo_bar');
4 
5// FooBar
1use Illuminate\Support\Str;
2 
3$converted = Str::studly('foo_bar');
4 
5// FooBar

Str::substr()

Str::substr 方法回傳字串中指定的起始位置開始指定長度的字串:

1use Illuminate\Support\Str;
2 
3$converted = Str::substr('The Laravel Framework', 4, 7);
4 
5// Laravel
1use Illuminate\Support\Str;
2 
3$converted = Str::substr('The Laravel Framework', 4, 7);
4 
5// Laravel

Str::substrCount()

Str::substrCount 方法回傳給定值中給定值出現的次數:

1use Illuminate\Support\Str;
2 
3$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');
4 
5// 2
1use Illuminate\Support\Str;
2 
3$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');
4 
5// 2

Str::substrReplace()

Str::substrreplace 方法在字串中取代其中一段文字,第三個引數指定起始位置,並以第四個引數來指定要取代的字元數。若第四個引數傳入 0,則會在指定位置插入字串,而不取代字串中現有的字元:

1use Illuminate\Support\Str;
2 
3$result = Str::substrReplace('1300', ':', 2);
4// 13:
5 
6$result = Str::substrReplace('1300', ':', 2, 0);
7// 13:00
1use Illuminate\Support\Str;
2 
3$result = Str::substrReplace('1300', ':', 2);
4// 13:
5 
6$result = Str::substrReplace('1300', ':', 2, 0);
7// 13:00

Str::swap()

Str::swap 方法使用 PHP 的 strtr 函式來取代給定字串中的多個值:

1use Illuminate\Support\Str;
2 
3$string = Str::swap([
4 'Tacos' => 'Burritos',
5 'great' => 'fantastic',
6], 'Tacos are great!');
7 
8// Burritos are fantastic!
1use Illuminate\Support\Str;
2 
3$string = Str::swap([
4 'Tacos' => 'Burritos',
5 'great' => 'fantastic',
6], 'Tacos are great!');
7 
8// Burritos are fantastic!

Str::title()

Str::title 方法將給定字串轉為 Title Case —— 標題用的大小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::title('a nice title uses the correct case');
4 
5// A Nice Title Uses The Correct Case
1use Illuminate\Support\Str;
2 
3$converted = Str::title('a nice title uses the correct case');
4 
5// A Nice Title Uses The Correct Case

Str::toHtmlString()

Str::toHtmlString 方法將字串實體轉換為 Illuminate\Support\HtmlString 的實體。HtmlString 實體可以在 Blade 樣板中顯示:

1use Illuminate\Support\Str;
2 
3$htmlString = Str::of('Nuno Maduro')->toHtmlString();
1use Illuminate\Support\Str;
2 
3$htmlString = Str::of('Nuno Maduro')->toHtmlString();

Str::ucfirst()

Str::ucfirst 方法回傳給定字串第一個字元轉為大寫後的字串:

1use Illuminate\Support\Str;
2 
3$string = Str::ucfirst('foo bar');
4 
5// Foo bar
1use Illuminate\Support\Str;
2 
3$string = Str::ucfirst('foo bar');
4 
5// Foo bar

Str::ucsplit()

Str::ucsplit 方法使用大寫字元來將給定字串拆分為陣列:

1use Illuminate\Support\Str;
2 
3$segments = Str::ucsplit('FooBar');
4 
5// [0 => 'Foo', 1 => 'Bar']
1use Illuminate\Support\Str;
2 
3$segments = Str::ucsplit('FooBar');
4 
5// [0 => 'Foo', 1 => 'Bar']

Str::upper()

Str::upper 方法將給定字串轉換為大寫:

1use Illuminate\Support\Str;
2 
3$string = Str::upper('laravel');
4 
5// LARAVEL
1use Illuminate\Support\Str;
2 
3$string = Str::upper('laravel');
4 
5// LARAVEL

Str::ulid()

Str::ulid 方法可產生 ULID:

1use Illuminate\Support\Str;
2 
3return (string) Str::ulid();
4 
5// 01gd6r360bp37zj17nxb55yv40
1use Illuminate\Support\Str;
2 
3return (string) Str::ulid();
4 
5// 01gd6r360bp37zj17nxb55yv40

Str::uuid()

Str::uuid 方法產生 UUID (第 4 版):

1use Illuminate\Support\Str;
2 
3return (string) Str::uuid();
1use Illuminate\Support\Str;
2 
3return (string) Str::uuid();

Str::wordCount()

Str::wordCount 方法回傳該字串中所包含的單詞數:

1use Illuminate\Support\Str;
2 
3Str::wordCount('Hello, world!'); // 2
1use Illuminate\Support\Str;
2 
3Str::wordCount('Hello, world!'); // 2

Str::words()

Str::words 方法將字串中的單詞數限制在指定數量內。也可以第三引數來傳入一個額外的字串,用來指定當字串被截斷時要加在最後方的內容:

1use Illuminate\Support\Str;
2 
3return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');
4 
5// Perfectly balanced, as >>>
1use Illuminate\Support\Str;
2 
3return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');
4 
5// Perfectly balanced, as >>>

str()

str 會回傳給定字串的 Illuminate\Support\Stringable 實體。這個函式與 Str::of 方法等價:

1$string = str('Taylor')->append(' Otwell');
2 
3// 'Taylor Otwell'
1$string = str('Taylor')->append(' Otwell');
2 
3// 'Taylor Otwell'

若沒有提供引數給 str 函式,則 str 會回傳一個 Illuminate\Support\Str 的實體:

1$snake = str()->snake('FooBar');
2 
3// 'foo_bar'
1$snake = str()->snake('FooBar');
2 
3// 'foo_bar'

trans()

trans 函式使用語系檔來翻譯給定的翻譯字串或翻譯索引鍵:

1echo trans('messages.welcome');
1echo trans('messages.welcome');

若指定的翻譯字串或翻譯索引鍵不存在時,trans 函式會回傳給定的值。因此,在上述範例中,若 messages.welcome 索引鍵不存在,trans 函式會回傳 messages.welcome

trans_choice()

trans_choice 函式會翻譯有詞形變化的翻譯索引鍵:

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

若指定的翻譯字串或翻譯索引鍵不存在時,trans_choice 函式會回傳給定的值。因此,在上述範例中,若 messages.notifications 索引鍵不存在,trans_choice 函式會回傳 messages.welcome

Fluent 字串

Fluent 字串提供處理字串值一個更流暢、物件導向的介面。我們可以串接多個字串操作,得到比起傳統字串操作來說更好閱讀的語法:

after

after 方法回傳字串中給定值以後的所有內容。若該字串中找不到給定值,會回傳整個字串:

1use Illuminate\Support\Str;
2 
3$slice = Str::of('This is my name')->after('This is');
4 
5// ' my name'
1use Illuminate\Support\Str;
2 
3$slice = Str::of('This is my name')->after('This is');
4 
5// ' my name'

afterLast

afterLast 方法回傳給定字串後最後一個出現給定值之後的所有內容。若找不到該值,會回傳整個字串:

1use Illuminate\Support\Str;
2 
3$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');
4 
5// 'Controller'
1use Illuminate\Support\Str;
2 
3$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');
4 
5// 'Controller'

append

append 方法將給定的值加到字串最後面:

1use Illuminate\Support\Str;
2 
3$string = Str::of('Taylor')->append(' Otwell');
4 
5// 'Taylor Otwell'
1use Illuminate\Support\Str;
2 
3$string = Str::of('Taylor')->append(' Otwell');
4 
5// 'Taylor Otwell'

ascii

ascii 方法會嘗試將給定字串翻譯為 ASCII 值:

1use Illuminate\Support\Str;
2 
3$string = Str::of('ü')->ascii();
4 
5// 'u'
1use Illuminate\Support\Str;
2 
3$string = Str::of('ü')->ascii();
4 
5// 'u'

basename

basename 方法回傳給定字串中最後一個名稱部分:

1use Illuminate\Support\Str;
2 
3$string = Str::of('/foo/bar/baz')->basename();
4 
5// 'baz'
1use Illuminate\Support\Str;
2 
3$string = Str::of('/foo/bar/baz')->basename();
4 
5// 'baz'

若有需要,也可以提供要從最後一個元件中移除的「副檔名」:

1use Illuminate\Support\Str;
2 
3$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');
4 
5// 'baz'
1use Illuminate\Support\Str;
2 
3$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');
4 
5// 'baz'

before

before 回傳字串在遇到給定值前的所有內容:

1use Illuminate\Support\Str;
2 
3$slice = Str::of('This is my name')->before('my name');
4 
5// 'This is '
1use Illuminate\Support\Str;
2 
3$slice = Str::of('This is my name')->before('my name');
4 
5// 'This is '

beforeLast

beforeLast 方法回傳字串中最後一次出現給定值以前的所有內容:

1use Illuminate\Support\Str;
2 
3$slice = Str::of('This is my name')->beforeLast('is');
4 
5// 'This '
1use Illuminate\Support\Str;
2 
3$slice = Str::of('This is my name')->beforeLast('is');
4 
5// 'This '

between

between 方法回傳介於兩個值之間的字串:

1use Illuminate\Support\Str;
2 
3$converted = Str::of('This is my name')->between('This', 'name');
4 
5// ' is my '
1use Illuminate\Support\Str;
2 
3$converted = Str::of('This is my name')->between('This', 'name');
4 
5// ' is my '

betweenFirst

betweenFirst 方法回傳介於兩個值之間,最小的可能字串部分:

1use Illuminate\Support\Str;
2 
3$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');
4 
5// 'a'
1use Illuminate\Support\Str;
2 
3$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');
4 
5// 'a'

camel

camel 方法將給定字串轉為 camelCase —— 駝峰命名法的大小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::of('foo_bar')->camel();
4 
5// fooBar
1use Illuminate\Support\Str;
2 
3$converted = Str::of('foo_bar')->camel();
4 
5// fooBar

classBasename

classBasename 方法回傳給定類別在移除類別 Namespace 後的類別名稱:

1use Illuminate\Support\Str;
2 
3$class = Str::of('Foo\Bar\Baz')->classBasename();
4 
5// Baz
1use Illuminate\Support\Str;
2 
3$class = Str::of('Foo\Bar\Baz')->classBasename();
4 
5// Baz

contains

contains 方法判斷給定字串是否包含給定值。該方法區分大小寫:

1use Illuminate\Support\Str;
2 
3$contains = Str::of('This is my name')->contains('my');
4 
5// true
1use Illuminate\Support\Str;
2 
3$contains = Str::of('This is my name')->contains('my');
4 
5// true

也可以傳入一組要判斷的陣列值,來判斷給定字串中是否有包含該陣列中任何一個值:

1use Illuminate\Support\Str;
2 
3$contains = Str::of('This is my name')->contains(['my', 'foo']);
4 
5// true
1use Illuminate\Support\Str;
2 
3$contains = Str::of('This is my name')->contains(['my', 'foo']);
4 
5// true

containsAll

containsAll 判斷給定字串是否有包含給定陣列中的所有值:

1use Illuminate\Support\Str;
2 
3$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);
4 
5// true
1use Illuminate\Support\Str;
2 
3$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);
4 
5// true

dirname

dirname 方法回傳給定字串中上層目錄的部分:

1use Illuminate\Support\Str;
2 
3$string = Str::of('/foo/bar/baz')->dirname();
4 
5// '/foo/bar'
1use Illuminate\Support\Str;
2 
3$string = Str::of('/foo/bar/baz')->dirname();
4 
5// '/foo/bar'

若有需要,也可以指定要去的多少層以上的目錄:

1use Illuminate\Support\Str;
2 
3$string = Str::of('/foo/bar/baz')->dirname(2);
4 
5// '/foo'
1use Illuminate\Support\Str;
2 
3$string = Str::of('/foo/bar/baz')->dirname(2);
4 
5// '/foo'

excerpt

excerpt 方法從給定字串中截取摘要,這個摘要符合該字串中第一個符合給定片語 (Phrase) 的實體:

1use Illuminate\Support\Str;
2 
3$excerpt = Str::of('This is my name')->excerpt('my', [
4 'radius' => 3
5]);
6 
7// '...is my na...'
1use Illuminate\Support\Str;
2 
3$excerpt = Str::of('This is my name')->excerpt('my', [
4 'radius' => 3
5]);
6 
7// '...is my na...'

radius 選項的預設值為 100。該選項可用來定義經過截取的字串中左右兩邊各需顯式多少個字元:

此外,也可使用 omission 選項來更改要加到截取字串前後的字串:

1use Illuminate\Support\Str;
2 
3$excerpt = Str::of('This is my name')->excerpt('name', [
4 'radius' => 3,
5 'omission' => '(...) '
6]);
7 
8// '(...) my name'
1use Illuminate\Support\Str;
2 
3$excerpt = Str::of('This is my name')->excerpt('name', [
4 'radius' => 3,
5 'omission' => '(...) '
6]);
7 
8// '(...) my name'

endsWith

endsWith 方法可判斷給定字串是否以給定值結尾:

1use Illuminate\Support\Str;
2 
3$result = Str::of('This is my name')->endsWith('name');
4 
5// true
1use Illuminate\Support\Str;
2 
3$result = Str::of('This is my name')->endsWith('name');
4 
5// true

也可以傳入一組陣列值來判斷給定字串的結尾是否符合該陣列內的其中一項:

1use Illuminate\Support\Str;
2 
3$result = Str::of('This is my name')->endsWith(['name', 'foo']);
4 
5// true
6 
7$result = Str::of('This is my name')->endsWith(['this', 'foo']);
8 
9// false
1use Illuminate\Support\Str;
2 
3$result = Str::of('This is my name')->endsWith(['name', 'foo']);
4 
5// true
6 
7$result = Str::of('This is my name')->endsWith(['this', 'foo']);
8 
9// false

exactly

exactly 方法判斷給定字串是否完全符合另一個字串:

1use Illuminate\Support\Str;
2 
3$result = Str::of('Laravel')->exactly('Laravel');
4 
5// true
1use Illuminate\Support\Str;
2 
3$result = Str::of('Laravel')->exactly('Laravel');
4 
5// true

explode

explode 方法以給定的分隔符號來拆分字串,並回傳一個包含分割後所有段落的 Collection:

1use Illuminate\Support\Str;
2 
3$collection = Str::of('foo bar baz')->explode(' ');
4 
5// collect(['foo', 'bar', 'baz'])
1use Illuminate\Support\Str;
2 
3$collection = Str::of('foo bar baz')->explode(' ');
4 
5// collect(['foo', 'bar', 'baz'])

finish

finish 方法會在給定字串不是以給定值結尾時,在該字串後方加上這個值:

1use Illuminate\Support\Str;
2 
3$adjusted = Str::of('this/string')->finish('/');
4 
5// this/string/
6 
7$adjusted = Str::of('this/string/')->finish('/');
8 
9// this/string/
1use Illuminate\Support\Str;
2 
3$adjusted = Str::of('this/string')->finish('/');
4 
5// this/string/
6 
7$adjusted = Str::of('this/string/')->finish('/');
8 
9// this/string/

headline

headline 方法將以大小寫、減號、底線等方式區隔的字串轉換為以空格區隔的字串,並將其中每個單詞的首字母都轉為大寫:

1use Illuminate\Support\Str;
2 
3$headline = Str::of('taylor_otwell')->headline();
4 
5// Taylor Otwell
6 
7$headline = Str::of('EmailNotificationSent')->headline();
8 
9// Email Notification Sent
1use Illuminate\Support\Str;
2 
3$headline = Str::of('taylor_otwell')->headline();
4 
5// Taylor Otwell
6 
7$headline = Str::of('EmailNotificationSent')->headline();
8 
9// Email Notification Sent

inlineMarkdown

inlineMarkdown 方法使用 CommonMarkdown 來將 GitHub Flavored Markdown 轉換為內嵌的 HTML。不過,與 markdown 不同,該方法不會將所有產生的 HTML 以區塊層級的元素包裝起來。

1use Illuminate\Support\Str;
2 
3$html = Str::of('**Laravel**')->inlineMarkdown();
4 
5// <strong>Laravel</strong>
1use Illuminate\Support\Str;
2 
3$html = Str::of('**Laravel**')->inlineMarkdown();
4 
5// <strong>Laravel</strong>

is

is 判斷給定字串是否符合給定的格式。可使用星號作為萬用字元:

1use Illuminate\Support\Str;
2 
3$matches = Str::of('foobar')->is('foo*');
4 
5// true
6 
7$matches = Str::of('foobar')->is('baz*');
8 
9// false
1use Illuminate\Support\Str;
2 
3$matches = Str::of('foobar')->is('foo*');
4 
5// true
6 
7$matches = Str::of('foobar')->is('baz*');
8 
9// false

isAscii

isAscii 方法判斷給定字串是否為 ASCII 字串:

1use Illuminate\Support\Str;
2 
3$result = Str::of('Taylor')->isAscii();
4 
5// true
6 
7$result = Str::of('ü')->isAscii();
8 
9// false
1use Illuminate\Support\Str;
2 
3$result = Str::of('Taylor')->isAscii();
4 
5// true
6 
7$result = Str::of('ü')->isAscii();
8 
9// false

isEmpty

isEmpty 方法判斷給定字串是否為空:

1use Illuminate\Support\Str;
2 
3$result = Str::of(' ')->trim()->isEmpty();
4 
5// true
6 
7$result = Str::of('Laravel')->trim()->isEmpty();
8 
9// false
1use Illuminate\Support\Str;
2 
3$result = Str::of(' ')->trim()->isEmpty();
4 
5// true
6 
7$result = Str::of('Laravel')->trim()->isEmpty();
8 
9// false

isNotEmpty

isNotEmpty 方法判斷給定字串是否不為空:

1use Illuminate\Support\Str;
2 
3$result = Str::of(' ')->trim()->isNotEmpty();
4 
5// false
6 
7$result = Str::of('Laravel')->trim()->isNotEmpty();
8 
9// true
1use Illuminate\Support\Str;
2 
3$result = Str::of(' ')->trim()->isNotEmpty();
4 
5// false
6 
7$result = Str::of('Laravel')->trim()->isNotEmpty();
8 
9// true

isJson

isJson 方法會判斷給定字串是否為有效的 JSON:

1use Illuminate\Support\Str;
2 
3$result = Str::of('[1,2,3]')->isJson();
4 
5// true
6 
7$result = Str::of('{"first": "John", "last": "Doe"}')->isJson();
8 
9// true
10 
11$result = Str::of('{first: "John", last: "Doe"}')->isJson();
12 
13// false
1use Illuminate\Support\Str;
2 
3$result = Str::of('[1,2,3]')->isJson();
4 
5// true
6 
7$result = Str::of('{"first": "John", "last": "Doe"}')->isJson();
8 
9// true
10 
11$result = Str::of('{first: "John", last: "Doe"}')->isJson();
12 
13// false

isUlid

isUlid 方法判斷給定字串是否為有效的 ULID:

1use Illuminate\Support\Str;
2 
3$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();
4 
5// true
6 
7$result = Str::of('Taylor')->isUlid();
8 
9// false
1use Illuminate\Support\Str;
2 
3$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();
4 
5// true
6 
7$result = Str::of('Taylor')->isUlid();
8 
9// false

isUuid

isUuid 方法判斷給定字串是否為有效的 UUID:

1use Illuminate\Support\Str;
2 
3$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();
4 
5// true
6 
7$result = Str::of('Taylor')->isUuid();
8 
9// false
1use Illuminate\Support\Str;
2 
3$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();
4 
5// true
6 
7$result = Str::of('Taylor')->isUuid();
8 
9// false

kebab

kebab 方法將給定字串轉換為 kebab-case —— Kebab 命名法的大小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::of('fooBar')->kebab();
4 
5// foo-bar
1use Illuminate\Support\Str;
2 
3$converted = Str::of('fooBar')->kebab();
4 
5// foo-bar

lcfirst

lcfirst 方法回傳給定字串第一個字元轉為小寫後的字串:

1use Illuminate\Support\Str;
2 
3$string = Str::of('Foo Bar')->lcfirst();
4 
5// foo Bar
1use Illuminate\Support\Str;
2 
3$string = Str::of('Foo Bar')->lcfirst();
4 
5// foo Bar

length

length 方法回傳給定字串的長度:

1use Illuminate\Support\Str;
2 
3$length = Str::of('Laravel')->length();
4 
5// 7
1use Illuminate\Support\Str;
2 
3$length = Str::of('Laravel')->length();
4 
5// 7

limit

limit 方法將給定字串截斷成指定長度:

1use Illuminate\Support\Str;
2 
3$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);
4 
5// The quick brown fox...
1use Illuminate\Support\Str;
2 
3$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);
4 
5// The quick brown fox...

也可以傳入第二個引數,以更改當字串被截斷時要加在最後方的內容:

1use Illuminate\Support\Str;
2 
3$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');
4 
5// The quick brown fox (...)
1use Illuminate\Support\Str;
2 
3$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');
4 
5// The quick brown fox (...)

lower

lower 方法將給定字串轉為小寫:

1use Illuminate\Support\Str;
2 
3$result = Str::of('LARAVEL')->lower();
4 
5// 'laravel'
1use Illuminate\Support\Str;
2 
3$result = Str::of('LARAVEL')->lower();
4 
5// 'laravel'

ltrim

ltrim 方法修剪字串左邊的值:

1use Illuminate\Support\Str;
2 
3$string = Str::of(' Laravel ')->ltrim();
4 
5// 'Laravel '
6 
7$string = Str::of('/Laravel/')->ltrim('/');
8 
9// 'Laravel/'
1use Illuminate\Support\Str;
2 
3$string = Str::of(' Laravel ')->ltrim();
4 
5// 'Laravel '
6 
7$string = Str::of('/Laravel/')->ltrim('/');
8 
9// 'Laravel/'

markdown

markdown 方法可將 GitHub Flavored Markdown 轉位為 HTML:

1use Illuminate\Support\Str;
2 
3$html = Str::of('# Laravel')->markdown();
4 
5// <h1>Laravel</h1>
6 
7$html = Str::of('# Taylor <b>Otwell</b>')->markdown([
8 'html_input' => 'strip',
9]);
10 
11// <h1>Taylor Otwell</h1>
1use Illuminate\Support\Str;
2 
3$html = Str::of('# Laravel')->markdown();
4 
5// <h1>Laravel</h1>
6 
7$html = Str::of('# Taylor <b>Otwell</b>')->markdown([
8 'html_input' => 'strip',
9]);
10 
11// <h1>Taylor Otwell</h1>

mask

mask 方法將字串中的一部分轉為重複字元,可用來為 E-Mail 位址或電話號碼⋯⋯等字串打碼(Obfuscate)

1use Illuminate\Support\Str;
2 
3$string = Str::of('[email protected]')->mask('*', 3);
4 
5// tay***************
1use Illuminate\Support\Str;
2 
3$string = Str::of('[email protected]')->mask('*', 3);
4 
5// tay***************

若有需要,也可以在 mask 方法的第三個或第四個引數上提供負數。提供負數時,會讓該方法從字串結尾處開始算起的給定距離開始打碼:

1$string = Str::of('[email protected]')->mask('*', -15, 3);
2 
3// tay***@example.com
4 
5$string = Str::of('[email protected]')->mask('*', 4, -4);
6 
7// tayl**********.com
1$string = Str::of('[email protected]')->mask('*', -15, 3);
2 
3// tay***@example.com
4 
5$string = Str::of('[email protected]')->mask('*', 4, -4);
6 
7// tayl**********.com

match

match 方法回傳字串中符合給定正規表示式格式的部分:

1use Illuminate\Support\Str;
2 
3$result = Str::of('foo bar')->match('/bar/');
4 
5// 'bar'
6 
7$result = Str::of('foo bar')->match('/foo (.*)/');
8 
9// 'bar'
1use Illuminate\Support\Str;
2 
3$result = Str::of('foo bar')->match('/bar/');
4 
5// 'bar'
6 
7$result = Str::of('foo bar')->match('/foo (.*)/');
8 
9// 'bar'

matchAll

matchAll 方法回傳一組 Collection,其中包含字串中所有符合給定正規表示式格式的部分:

1use Illuminate\Support\Str;
2 
3$result = Str::of('bar foo bar')->matchAll('/bar/');
4 
5// collect(['bar', 'bar'])
1use Illuminate\Support\Str;
2 
3$result = Str::of('bar foo bar')->matchAll('/bar/');
4 
5// collect(['bar', 'bar'])

也可以在正規式中指定分組(Matching Group),Laravel 會回傳一個包含這些分組的 Collection:

1use Illuminate\Support\Str;
2 
3$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');
4 
5// collect(['un', 'ly']);
1use Illuminate\Support\Str;
2 
3$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');
4 
5// collect(['un', 'ly']);

若未找到相符合的內容,會回傳空 Collection。

newLine

newLine 方法為字串的最後加上一個「EOL (End of Line,行結尾)」字元:

1use Illuminate\Support\Str;
2 
3$padded = Str::of('Laravel')->newLine()->append('Framework');
4 
5// 'Laravel
6// Framework'
1use Illuminate\Support\Str;
2 
3$padded = Str::of('Laravel')->newLine()->append('Framework');
4 
5// 'Laravel
6// Framework'

padBoth

padBoth 方法包裝了 PHP 的 str_path 方法,會填充字串的兩端,直到字串符合預期的長度:

1use Illuminate\Support\Str;
2 
3$padded = Str::of('James')->padBoth(10, '_');
4 
5// '__James___'
6 
7$padded = Str::of('James')->padBoth(10);
8 
9// ' James '
1use Illuminate\Support\Str;
2 
3$padded = Str::of('James')->padBoth(10, '_');
4 
5// '__James___'
6 
7$padded = Str::of('James')->padBoth(10);
8 
9// ' James '

padLeft

padLeft 包裝了 PHP 的 str_pad 方法,會使用另一個字串填充給定字串的左邊,直到符合預期的長度:

1use Illuminate\Support\Str;
2 
3$padded = Str::of('James')->padLeft(10, '-=');
4 
5// '-=-=-James'
6 
7$padded = Str::of('James')->padLeft(10);
8 
9// ' James'
1use Illuminate\Support\Str;
2 
3$padded = Str::of('James')->padLeft(10, '-=');
4 
5// '-=-=-James'
6 
7$padded = Str::of('James')->padLeft(10);
8 
9// ' James'

padRight

padRight 包裝了 PHP 的 str_pad 方法,會使用另一個字串填充給定字串的右邊,直到符合預期的長度:

1use Illuminate\Support\Str;
2 
3$padded = Str::of('James')->padRight(10, '-');
4 
5// 'James-----'
6 
7$padded = Str::of('James')->padRight(10);
8 
9// 'James '
1use Illuminate\Support\Str;
2 
3$padded = Str::of('James')->padRight(10, '-');
4 
5// 'James-----'
6 
7$padded = Str::of('James')->padRight(10);
8 
9// 'James '

pipe

pipe 方法會講目前字串傳入給定的閉包內,來讓我們變換字串:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');
5 
6// 'Checksum: a5c95b86291ea299fcbe64458ed12702'
7 
8$closure = Str::of('foo')->pipe(function (Stringable $str) {
9 return 'bar';
10});
11 
12// 'bar'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');
5 
6// 'Checksum: a5c95b86291ea299fcbe64458ed12702'
7 
8$closure = Str::of('foo')->pipe(function (Stringable $str) {
9 return 'bar';
10});
11 
12// 'bar'

plural

plural 方法將單數單詞轉換為其複數形態。該方法支援所有 Laravel Pluralizer 所支援的語言

1use Illuminate\Support\Str;
2 
3$plural = Str::of('car')->plural();
4 
5// cars
6 
7$plural = Str::of('child')->plural();
8 
9// children
1use Illuminate\Support\Str;
2 
3$plural = Str::of('car')->plural();
4 
5// cars
6 
7$plural = Str::of('child')->plural();
8 
9// children

也可以提供一個整數作為該方法的第二個引數,用來判斷要取得該字串的單數或複數型:

1use Illuminate\Support\Str;
2 
3$plural = Str::of('child')->plural(2);
4 
5// children
6 
7$plural = Str::of('child')->plural(1);
8 
9// child
1use Illuminate\Support\Str;
2 
3$plural = Str::of('child')->plural(2);
4 
5// children
6 
7$plural = Str::of('child')->plural(1);
8 
9// child

prepend

prepend 方法將給定的值加到字串最後面:

1use Illuminate\Support\Str;
2 
3$string = Str::of('Framework')->prepend('Laravel ');
4 
5// Laravel Framework
1use Illuminate\Support\Str;
2 
3$string = Str::of('Framework')->prepend('Laravel ');
4 
5// Laravel Framework

remove

remove 方法從字串中移除給定的一個或多個值:

1use Illuminate\Support\Str;
2 
3$string = Str::of('Arkansas is quite beautiful!')->remove('quite');
4 
5// Arkansas is beautiful!
1use Illuminate\Support\Str;
2 
3$string = Str::of('Arkansas is quite beautiful!')->remove('quite');
4 
5// Arkansas is beautiful!

也可以傳入 false 作為第二個引數,來在移除字串時忽略大小寫差異:

replace

replace 方法在字串中取代給定字串:

1use Illuminate\Support\Str;
2 
3$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');
4 
5// Laravel 7.x
1use Illuminate\Support\Str;
2 
3$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');
4 
5// Laravel 7.x

replaceArray

replaceArray 函式使用陣列來依序在陣列中取代給定的值:

1use Illuminate\Support\Str;
2 
3$string = 'The event will take place between ? and ?';
4 
5$replaced = Str::of($string)->replaceArray('?', ['8:30', '9:00']);
6 
7// The event will take place between 8:30 and 9:00
1use Illuminate\Support\Str;
2 
3$string = 'The event will take place between ? and ?';
4 
5$replaced = Str::of($string)->replaceArray('?', ['8:30', '9:00']);
6 
7// The event will take place between 8:30 and 9:00

replaceFirst

replaceFirst 方法取代字串中第一次出現的給定值:

1use Illuminate\Support\Str;
2 
3$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a');
4 
5// a quick brown fox jumps over the lazy dog
1use Illuminate\Support\Str;
2 
3$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a');
4 
5// a quick brown fox jumps over the lazy dog

replaceLast

replaceLast 方法取代字串中最後一次出現的給定值:

1use Illuminate\Support\Str;
2 
3$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a');
4 
5// the quick brown fox jumps over a lazy dog
1use Illuminate\Support\Str;
2 
3$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a');
4 
5// the quick brown fox jumps over a lazy dog

replaceMatches

replaceMatches 方法使用給定取代字串來取代字串中所有符合格式的部分:

1use Illuminate\Support\Str;
2 
3$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '')
4 
5// '15015551000'
1use Illuminate\Support\Str;
2 
3$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '')
4 
5// '15015551000'

replaceMatches 也接受一個閉包,每當有符合格式的部分時,就會將符合的部分傳給該閉包,讓我們能在閉包內處理取代邏輯,並在閉包內回傳要取代的值:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$replaced = Str::of('123')->replaceMatches('/\d/', function (array $matches) {
5 return '['.$matches[0].']';
6});
7 
8// '[1][2][3]'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$replaced = Str::of('123')->replaceMatches('/\d/', function (array $matches) {
5 return '['.$matches[0].']';
6});
7 
8// '[1][2][3]'

rtrim

rtrim 方法修剪字串右邊的值:

1use Illuminate\Support\Str;
2 
3$string = Str::of(' Laravel ')->rtrim();
4 
5// ' Laravel'
6 
7$string = Str::of('/Laravel/')->rtrim('/');
8 
9// '/Laravel'
1use Illuminate\Support\Str;
2 
3$string = Str::of(' Laravel ')->rtrim();
4 
5// ' Laravel'
6 
7$string = Str::of('/Laravel/')->rtrim('/');
8 
9// '/Laravel'

scan

scan 方法依照給定的格式來講輸入字串解析為 Collection。給定的格式為 sscanf PHP 函式所支援的:

1use Illuminate\Support\Str;
2 
3$collection = Str::of('filename.jpg')->scan('%[^.].%s');
4 
5// collect(['filename', 'jpg'])
1use Illuminate\Support\Str;
2 
3$collection = Str::of('filename.jpg')->scan('%[^.].%s');
4 
5// collect(['filename', 'jpg'])

singular

plural 方法將單詞轉換為其單數形態。該方法支援所有 Laravel Pluralizer 所支援的語言

1use Illuminate\Support\Str;
2 
3$singular = Str::of('cars')->singular();
4 
5// car
6 
7$singular = Str::of('children')->singular();
8 
9// child
1use Illuminate\Support\Str;
2 
3$singular = Str::of('cars')->singular();
4 
5// car
6 
7$singular = Str::of('children')->singular();
8 
9// child

slug

slug 方法以給定字串產生適合在 URL 中使用的「Slug」格式:

1use Illuminate\Support\Str;
2 
3$slug = Str::of('Laravel Framework')->slug('-');
4 
5// laravel-framework
1use Illuminate\Support\Str;
2 
3$slug = Str::of('Laravel Framework')->slug('-');
4 
5// laravel-framework

snake

snake 方法將給定字串轉為 snake_case —— 蛇型命名法的大小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::of('fooBar')->snake();
4 
5// foo_bar
1use Illuminate\Support\Str;
2 
3$converted = Str::of('fooBar')->snake();
4 
5// foo_bar

split

split 方法使用正規表示式來將字串拆分為 Collection:

1use Illuminate\Support\Str;
2 
3$segments = Str::of('one, two, three')->split('/[\s,]+/');
4 
5// collect(["one", "two", "three"])
1use Illuminate\Support\Str;
2 
3$segments = Str::of('one, two, three')->split('/[\s,]+/');
4 
5// collect(["one", "two", "three"])

squish

squish 方法會從字串內移除所有多餘的空格,其中亦包含單詞間多餘的空格:

1use Illuminate\Support\Str;
2 
3$string = Str::of(' laravel framework ')->squish();
4 
5// laravel framework
1use Illuminate\Support\Str;
2 
3$string = Str::of(' laravel framework ')->squish();
4 
5// laravel framework

start

start 方法會在給定字串不是以給定值起始時,在該字串前方加上這個值:

1use Illuminate\Support\Str;
2 
3$adjusted = Str::of('this/string')->start('/');
4 
5// /this/string
6 
7$adjusted = Str::of('/this/string')->start('/');
8 
9// /this/string
1use Illuminate\Support\Str;
2 
3$adjusted = Str::of('this/string')->start('/');
4 
5// /this/string
6 
7$adjusted = Str::of('/this/string')->start('/');
8 
9// /this/string

startsWith

startsWith` 方法可判斷給定字串是否以給定值起始:

1use Illuminate\Support\Str;
2 
3$result = Str::of('This is my name')->startsWith('This');
4 
5// true
1use Illuminate\Support\Str;
2 
3$result = Str::of('This is my name')->startsWith('This');
4 
5// true

studly

studly 方法將給定字串轉為 StudlyCase —— Studly 命名法的大小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::of('foo_bar')->studly();
4 
5// FooBar
1use Illuminate\Support\Str;
2 
3$converted = Str::of('foo_bar')->studly();
4 
5// FooBar

substr

substr 方法回傳字串中指定的起始位置開始指定長度的字串:

1use Illuminate\Support\Str;
2 
3$string = Str::of('Laravel Framework')->substr(8);
4 
5// Framework
6 
7$string = Str::of('Laravel Framework')->substr(8, 5);
8 
9// Frame
1use Illuminate\Support\Str;
2 
3$string = Str::of('Laravel Framework')->substr(8);
4 
5// Framework
6 
7$string = Str::of('Laravel Framework')->substr(8, 5);
8 
9// Frame

substrReplace

substrReplace 方法在字串中取代其中一段文字,第二個引數指定起始位置,並以第三個引數來指定要取代的字元數。若第三個引數傳入 0,則會在指定位置插入字串,而不取代字串中現有的字元:

1use Illuminate\Support\Str;
2 
3$string = Str::of('1300')->substrReplace(':', 2);
4 
5// 13:
6 
7$string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0);
8 
9// The Laravel Framework
1use Illuminate\Support\Str;
2 
3$string = Str::of('1300')->substrReplace(':', 2);
4 
5// 13:
6 
7$string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0);
8 
9// The Laravel Framework

swap

swap 方法使用 PHP 的 strtr 函式來取代給定字串中的多個值:

1use Illuminate\Support\Str;
2 
3$string = Str::of('Tacos are great!')
4 ->swap([
5 'Tacos' => 'Burritos',
6 'great' => 'fantastic',
7 ]);
8 
9// Burritos are fantastic!
1use Illuminate\Support\Str;
2 
3$string = Str::of('Tacos are great!')
4 ->swap([
5 'Tacos' => 'Burritos',
6 'great' => 'fantastic',
7 ]);
8 
9// Burritos are fantastic!

tap

tap 方法將目前字串傳入給定的閉包內,讓我們可以在不影響目前字串的情況下檢視與處理該字串。無論該閉包回傳什麼,tap 都會回傳原始字串:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('Laravel')
5 ->append(' Framework')
6 ->tap(function (Stringable $string) {
7 dump('String after append: '.$string);
8 })
9 ->upper();
10 
11// LARAVEL FRAMEWORK
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('Laravel')
5 ->append(' Framework')
6 ->tap(function (Stringable $string) {
7 dump('String after append: '.$string);
8 })
9 ->upper();
10 
11// LARAVEL FRAMEWORK

test

test 方法判斷目前字串是否符合給定的正規表示式:

1use Illuminate\Support\Str;
2 
3$result = Str::of('Laravel Framework')->test('/Laravel/');
4 
5// true
1use Illuminate\Support\Str;
2 
3$result = Str::of('Laravel Framework')->test('/Laravel/');
4 
5// true

title

title 方法將給定字串轉為 Title Case —— 標題用的大小寫:

1use Illuminate\Support\Str;
2 
3$converted = Str::of('a nice title uses the correct case')->title();
4 
5// A Nice Title Uses The Correct Case
1use Illuminate\Support\Str;
2 
3$converted = Str::of('a nice title uses the correct case')->title();
4 
5// A Nice Title Uses The Correct Case

trim

trim 方法修剪字串值:

1use Illuminate\Support\Str;
2 
3$string = Str::of(' Laravel ')->trim();
4 
5// 'Laravel'
6 
7$string = Str::of('/Laravel/')->trim('/');
8 
9// 'Laravel'
1use Illuminate\Support\Str;
2 
3$string = Str::of(' Laravel ')->trim();
4 
5// 'Laravel'
6 
7$string = Str::of('/Laravel/')->trim('/');
8 
9// 'Laravel'

ucfirst

ucfirst 方法回傳給定字串第一個字元轉為大寫後的字串:

1use Illuminate\Support\Str;
2 
3$string = Str::of('foo bar')->ucfirst();
4 
5// Foo bar
1use Illuminate\Support\Str;
2 
3$string = Str::of('foo bar')->ucfirst();
4 
5// Foo bar

ucsplit

ucsplit 方法使用大寫字元來將給定字串拆分為陣列:

1use Illuminate\Support\Str;
2 
3$string = Str::of('Foo Bar')->ucsplit();
4 
5// collect(['Foo', 'Bar'])
1use Illuminate\Support\Str;
2 
3$string = Str::of('Foo Bar')->ucsplit();
4 
5// collect(['Foo', 'Bar'])

upper

upper 方法將給定字串轉換為大寫:

1use Illuminate\Support\Str;
2 
3$adjusted = Str::of('laravel')->upper();
4 
5// LARAVEL
1use Illuminate\Support\Str;
2 
3$adjusted = Str::of('laravel')->upper();
4 
5// LARAVEL

when

when 方法會在給定條件為 true 時叫用給定閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('Taylor')
5 ->when(true, function (Stringable $string) {
6 return $string->append(' Otwell');
7 });
8 
9// 'Taylor Otwell'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('Taylor')
5 ->when(true, function (Stringable $string) {
6 return $string->append(' Otwell');
7 });
8 
9// 'Taylor Otwell'

若有需要,也可以傳入另一個閉包作為第三個引數給 when 方法。第三個引數上的閉包會在條件參數為 false 時被執行。

whenContains

whenContains 方法會在字串包含給定值時叫用給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('tony stark')
5 ->whenContains('tony', function (Stringable $string) {
6 return $string->title();
7 });
8 
9// 'Tony Stark'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('tony stark')
5 ->whenContains('tony', function (Stringable $string) {
6 return $string->title();
7 });
8 
9// 'Tony Stark'

若有需要,也可以傳入另一個閉包作為第三個引數給 whenContains 方法。當字串內未包含給定值時會執行第三個引數上的閉包。

也可以傳入一組要判斷的陣列值,來判斷給定字串中是否有包含該陣列中任何一個值:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('tony stark')
5 ->whenContains(['tony', 'hulk'], function (Stringable $string) {
6 return $string->title();
7 });
8 
9// Tony Stark
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('tony stark')
5 ->whenContains(['tony', 'hulk'], function (Stringable $string) {
6 return $string->title();
7 });
8 
9// Tony Stark

whenContainsAll

whenContainsAll 方法會在字串包含所有給定的子字串時叫用給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('tony stark')
5 ->whenContainsAll(['tony', 'stark'], function (Stringable $string) {
6 return $string->title();
7 });
8 
9// 'Tony Stark'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('tony stark')
5 ->whenContainsAll(['tony', 'stark'], function (Stringable $string) {
6 return $string->title();
7 });
8 
9// 'Tony Stark'

若有需要,也可以傳入另一個閉包作為第三個引數給 when 方法。第三個引數上的閉包會在條件參數為 false 時被執行。

whenEmpty

whenEmpty 方法會在目前字串為空時叫用給定的閉包。若該閉包有回傳值,則 whenEmpty 方法會回傳這個值。若該閉包無回傳值,則會回傳 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of(' ')->whenEmpty(function (Stringable $string) {
5 return $string->trim()->prepend('Laravel');
6});
7 
8// 'Laravel'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of(' ')->whenEmpty(function (Stringable $string) {
5 return $string->trim()->prepend('Laravel');
6});
7 
8// 'Laravel'

whenNotEmpty

whenNotEmpty 方法會在目前字串不為空時叫用給定的閉包。若該閉包有回傳值,則 whenNotEmpty 方法會回傳這個值。若該閉包無回傳值,則會回傳 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('Framework')->whenNotEmpty(function (Stringable $string) {
5 return $string->prepend('Laravel ');
6});
7 
8// 'Laravel Framework'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('Framework')->whenNotEmpty(function (Stringable $string) {
5 return $string->prepend('Laravel ');
6});
7 
8// 'Laravel Framework'

whenStartsWith

whenStartsWith 方法會在字串以給定子字串開頭時叫用給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('disney world')->whenStartsWith('disney', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Disney World'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('disney world')->whenStartsWith('disney', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Disney World'

whenEndsWith

whenEndsWith 方法會在字串以給定子字串結尾時叫用給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('disney world')->whenEndsWith('world', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Disney World'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('disney world')->whenEndsWith('world', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Disney World'

whenExactly

whenExactly 方法會在目前字串符合給定字串時叫用給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('laravel')->whenExactly('laravel', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Laravel'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('laravel')->whenExactly('laravel', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Laravel'

whenNotExactly

whenNotExactly 方法會在目前字串不符合給定字串時呼叫給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('framework')->whenNotExactly('laravel', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Framework'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('framework')->whenNotExactly('laravel', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Framework'

whenIs

whenIs 方法會在目前字串符合給定格式時叫用給定的閉包。可使用星號作為萬用字元。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('foo/bar')->whenIs('foo/*', function (Stringable $string) {
5 return $string->append('/baz');
6});
7 
8// 'foo/bar/baz'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('foo/bar')->whenIs('foo/*', function (Stringable $string) {
5 return $string->append('/baz');
6});
7 
8// 'foo/bar/baz'

whenIsAscii

whenIsAscii 方法會在目前字串為 7 位元 ASCII 時叫用給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Laravel'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Laravel'

whenIsUlid

whenIsUlis 方法會在目前字串為有效 ULID 時叫用給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2 
3$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function (Stringable $string) {
4 return $string->substr(0, 8);
5});
6 
7// '01gd6r36'
1use Illuminate\Support\Str;
2 
3$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function (Stringable $string) {
4 return $string->substr(0, 8);
5});
6 
7// '01gd6r36'

whenIsUuid

whenIsUuis 方法會在目前字串為有效 UUID 時叫用給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function (Stringable $string) {
5 return $string->substr(0, 8);
6});
7 
8// 'a0a2a2d2'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function (Stringable $string) {
5 return $string->substr(0, 8);
6});
7 
8// 'a0a2a2d2'

whenTest

whenTest 方法會在字串符合給定的正規表示式時叫用給定的閉包。該閉包會收到 Fluent 字串實體:

1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('laravel framework')->whenTest('/laravel/', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Laravel Framework'
1use Illuminate\Support\Str;
2use Illuminate\Support\Stringable;
3 
4$string = Str::of('laravel framework')->whenTest('/laravel/', function (Stringable $string) {
5 return $string->title();
6});
7 
8// 'Laravel Framework'

wordCount

wordCount 方法回傳該字串中所包含的單詞數:

1use Illuminate\Support\Str;
2 
3Str::of('Hello, world!')->wordCount(); // 2
1use Illuminate\Support\Str;
2 
3Str::of('Hello, world!')->wordCount(); // 2

words

words 方法可限制字串中的單詞數。若有需要,可以指定一個額外的字串來附加到截斷的字串上:

1use Illuminate\Support\Str;
2 
3$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');
4 
5// Perfectly balanced, as >>>
1use Illuminate\Support\Str;
2 
3$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');
4 
5// Perfectly balanced, as >>>

URL

action()

action 方法可為給定的 Controller 動作產生 URL:

1use App\Http\Controllers\HomeController;
2 
3$url = action([HomeController::class, 'index']);
1use App\Http\Controllers\HomeController;
2 
3$url = action([HomeController::class, 'index']);

若該方法接受 Route 參數,請將這些 Route 參數作為第二個引數傳給該方法:

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

asset()

asset 方法使用目前 Request 的 Scheme (HTTP 或 HTTPS) 來產生素材 URL:

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

可以在 .env 檔案中設定 ASSET_URL 變數來設定素材 URL 的主機名稱。若你將素材放在如 Amazon S3 或其他 CDN 之類的外部服務上,就很適合這樣設定:

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

route()

route 函式產生給定命名 Route 的 URL:

1$url = route('route.name');
1$url = route('route.name');

若該 Route 接受參數,請將這些參數作為第二個引數傳給該方法:

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

預設情況下,route 函式回傳絕對 URL。若想產生相對 URL,請傳入 false 作為第三個引數給該函式:

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

secure_asset()

secure_asset 函式使用 HTTPS 為素材產生 URL:

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

secure_url()

secure_url 函式產生給定路徑上的完整名稱 HTTPS URL。可以傳入額外的 URL 片段給該函式的第二個引數:

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

to_route()

to_route 函式為給定的命名 Route 產生一個重新導向的 HTTP Response

1return to_route('users.show', ['user' => 1]);
1return to_route('users.show', ['user' => 1]);

若有需要,也可以傳入一個用於跳轉的 HTTP 狀態碼以及一些額外的回應標頭作為 to_route 方法的第三與第四個引數:

1return to_route('users.show', ['user' => 1], 302, ['X-Framework' => 'Laravel']);
1return to_route('users.show', ['user' => 1], 302, ['X-Framework' => 'Laravel']);

url()

url 函式可以產生給定路徑上的完整名稱 URL:

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

若未提供路徑,則會回傳 Illuminate\Routing\UrlGenerator 實體:

1$current = url()->current();
2 
3$full = url()->full();
4 
5$previous = url()->previous();
1$current = url()->current();
2 
3$full = url()->full();
4 
5$previous = url()->previous();

其他

abort()

abort 函式會擲回 HTTP Exception。HTTP Exception 會被 Exception Handler(例外處理常式) 轉譯:

1abort(403);
1abort(403);

也可以提供 Exception 訊息與要傳送給瀏覽器的自訂 HTTP Response 標頭:

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

abort_if()

abort_if 函式會在給定布林運算式取值為 true 時擲回一個 HTTP Exception:

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

abort 方法類似,我們也可以在第三個引數上提供 Exception 的 Response 文字,並在第四個引數上提供一組自訂 Response 標頭陣列。

abort_unless()

abort_unless 函式會在給定布林運算式取值為 false 時擲回一個 HTTP Exception:

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

abort 方法類似,我們也可以在第三個引數上提供 Exception 的 Response 文字,並在第四個引數上提供一組自訂 Response 標頭陣列。

app()

app 函式回傳 Service Container 實體:

1$container = app();
1$container = app();

也可以傳入一個類別或介面名稱來用 Container 解析:

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

auth()

auth 函式回傳 Authenticator 的實體。可以使用 auth 函式來作為 Auth Facade 的替代:

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

若有需要,可以指定要存取的 Guard 實體:

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

back()

back 函式產生一個指向使用者上一個瀏覽位置的[重新導向 HTTP Response]:

1return back($status = 302, $headers = [], $fallback = '/');
2 
3return back();
1return back($status = 302, $headers = [], $fallback = '/');
2 
3return back();

bcrypt()

bcrypt 方法使用 Bcrypt 來雜湊給定的值。也可以使用這個函式來作為 Hash Facade 的替代:

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

blank()

blank 函式判斷給定值是否為「空白(Blank)」:

1blank('');
2blank(' ');
3blank(null);
4blank(collect());
5 
6// true
7 
8blank(0);
9blank(true);
10blank(false);
11 
12// false
1blank('');
2blank(' ');
3blank(null);
4blank(collect());
5 
6// true
7 
8blank(0);
9blank(true);
10blank(false);
11 
12// false

請參考 filled 方法以瞭解與 blank 相反的方法。

broadcast()

broadcast 函式會廣播給定的 Event 給其 Listener:

1broadcast(new UserRegistered($user));
2 
3broadcast(new UserRegistered($user))->toOthers();
1broadcast(new UserRegistered($user));
2 
3broadcast(new UserRegistered($user))->toOthers();

cache()

cache 函式可用來從快取中取值。若快取中沒有給定的索引鍵,則會回傳可選的預設值:

1$value = cache('key');
2 
3$value = cache('key', 'default');
1$value = cache('key');
2 
3$value = cache('key', 'default');

可以傳入一組索引鍵 / 值配對的陣列給該函式來將項目加入快取中。也請傳入單位為秒的快取值有效期間:

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

class_uses_recursive()

class_uses_recursive 函式回傳某個類別使用的所有 Trait,包含其所有上層(Parent)類別使用的 Trait:

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

collect()

collect 函式使用給定值來建立一個 Collection 實體:

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

config()

config 函式可取得設定變數中的值。設定值可以通過「點 (.)」語法來存取,即包含設定檔名稱與欲存取的選項名。也可以指定設定選項不存在時要回傳的預設值:

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

也可以在執行階段傳入一組索引鍵 / 值配對的陣列來設定設定值。不過,請注意,該函式只會影響目前 Request 的設定值,並不會實際更新設定:

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

cookie 函式建立一個新的 Cookie 實體:

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

csrf_field()

csrf_field 函式產生一個包含 CSRF Token 的 HTML hidden 輸入欄位。舉例來說,在 Blade 語法中可這樣使用:

1{{ csrf_field() }}
1{{ csrf_field() }}

csrf_token()

csrf_token 函式可取得目前 CSRF Token 的值:

1$token = csrf_token();
1$token = csrf_token();

decrypt()

decrypt 函式會解密給定的值。可使用這個方法作為 Crypt Facade 的替代。

1$password = decrypt($value);
1$password = decrypt($value);

dd()

dd 函式可傾印給定變數,並結束目前的指令碼執行:

1dd($value);
2 
3dd($value1, $value2, $value3, ...);
1dd($value);
2 
3dd($value1, $value2, $value3, ...);

若不想結束目前的指令碼執行,請改為使用 dump 方法。

dispatch()

dispatch 方法將給定 Job 推入 Laravel 的 Job 佇列 中:

1dispatch(new App\Jobs\SendEmails);
1dispatch(new App\Jobs\SendEmails);

dump()

dump 函式傾印給定的變數:

1dump($value);
2 
3dump($value1, $value2, $value3, ...);
1dump($value);
2 
3dump($value1, $value2, $value3, ...);

若想在傾印變數後停止執行指令碼,請使用 dd 函式來代替。

encrypt()

encrypt 函式會加密給定的值。可使用這個方法作為 Crypt Facade 的替代:

1$secret = encrypt('my-secret-value');
1$secret = encrypt('my-secret-value');

env()

env 函式可取得環境變數的值,或是回傳預設值:

1$env = env('APP_ENV');
2 
3$env = env('APP_ENV', 'production');
1$env = env('APP_ENV');
2 
3$env = env('APP_ENV', 'production');
exclamation

若在部署流程中執行了 config:cache 指令,應確保只有在設定檔中呼叫 env 函式。設定檔被快取後,就不會再載入 .env 檔了。所有 env 函式查詢 .env 變數的呼叫都會回傳 null

event()

event 函式將給定 Event 分派(Dispatch)給其 Listener:

1event(new UserRegistered($user));
1event(new UserRegistered($user));

fake()

fake 方法會從 Container 中解析 Faker 單例 (Singleton),很適合在 Model Factory、資料庫 Seeder、測試、打樣 View 等地方建立假資料:

1@for($i = 0; $i < 10; $i++)
2 <dl>
3 <dt>Name</dt>
4 <dd>{{ fake()->name() }}</dd>
5 
6 <dt>Email</dt>
7 <dd>{{ fake()->unique()->safeEmail() }}</dd>
8 </dl>
9@endfor
1@for($i = 0; $i < 10; $i++)
2 <dl>
3 <dt>Name</dt>
4 <dd>{{ fake()->name() }}</dd>
5 
6 <dt>Email</dt>
7 <dd>{{ fake()->unique()->safeEmail() }}</dd>
8 </dl>
9@endfor

預設情況下,fake 函式會使用 config/app.php 設定檔中的 app.faker_locale 設定選項。不過,也可以將地區選項傳入 fake 函式來指定地區。每個地區選項都會被解析為個別的單例:

1fake('nl_NL')->name()
1fake('nl_NL')->name()

filled()

filled 函式判斷給定值是否不為「空白(Blank)」:

1filled(0);
2filled(true);
3filled(false);
4 
5// true
6 
7filled('');
8filled(' ');
9filled(null);
10filled(collect());
11 
12// false
1filled(0);
2filled(true);
3filled(false);
4 
5// true
6 
7filled('');
8filled(' ');
9filled(null);
10filled(collect());
11 
12// false

請參考 blank 方法以瞭解與 filled 相反的方法。

info()

info 函式寫入 info 等級的資訊至程式的 日誌 中:

1info('Some helpful information!');
1info('Some helpful information!');

也可以傳入一組包含上下文資料的陣列給該函式:

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

logger()

logger 函式可用來寫入 debug 等級的訊息至日誌中:

1logger('Debug message');
1logger('Debug message');

也可以傳入一組包含上下文資料的陣列給該函式:

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

若未傳入任何值給該方法,則會回傳 Logger 實體:

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

method_field()

method_field 函式產生一個用於模擬表單 HTTP 動詞的 HTML hidden 輸入欄位。舉例來說,在 Blade 語法中可這樣使用:

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

now()

now 函式建立一個目前時間的新 Illuminate\Support\Carbon 實體:

1$now = now();
1$now = now();

old()

old 函式取得快閃存入 Session 的舊輸入值:

1$value = old('value');
2 
3$value = old('value', 'default');
1$value = old('value');
2 
3$value = old('value', 'default');

由於提供給 old 方法第二個引數的「預設值」常常都是 Eloquent Model 的屬性,因此,在 Laravel 中,我們可以直接將整個 Eloquent Model 作為第二個引數傳給 old 方法即可。當我們傳入 Eloquent Model 給 old 方法時,Laravel 會假設傳給 old 方法的第一個引數即為要當作「預設值」的 Eloquent 屬性名稱:

1{{ old('name', $user->name) }}
2 
3// 等同於...
4 
5{{ old('name', $user) }}
1{{ old('name', $user->name) }}
2 
3// 等同於...
4 
5{{ old('name', $user) }}

optional()

optional 函式接受任何的引數,並可讓你存取該物件上的屬性或呼叫該物件上的方法。若給定的物件為 null,存取屬性和方法時會回傳 null 而不是發生錯誤:

1return optional($user->address)->street;
2 
3{!! old('name', optional($user)->name) !!}
1return optional($user->address)->street;
2 
3{!! old('name', optional($user)->name) !!}

optional 函式也接受閉包作為其第二個引數。若第一個引數傳入的值不是 null 時會叫用該閉包:

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

policy()

policy 方法取得給定類別的 Policy 實體:

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

redirect()

redirect 函式回傳一個重新導向的 HTTP Response。若呼叫時未提供任何引數,則回傳 Redirector 實體:

1return redirect($to = null, $status = 302, $headers = [], $https = null);
2 
3return redirect('/home');
4 
5return redirect()->route('route.name');
1return redirect($to = null, $status = 302, $headers = [], $https = null);
2 
3return redirect('/home');
4 
5return redirect()->route('route.name');

report()

report 函式會使用 Exception Handler 來回報 Exception:

1report($e);
1report($e);

report 函式也接受一個字串作為其引數。若傳入字串給該函式時,report 會使用給定的字串作為訊息來建立 Exception:

1report('Something went wrong.');
1report('Something went wrong.');

report_if()

report_if 函式會在給定條件為 true 時使用 Exception Handler 來回報 Exception:

1report_if($shouldReport, $e);
2 
3report_if($shouldReport, 'Something went wrong.');
1report_if($shouldReport, $e);
2 
3report_if($shouldReport, 'Something went wrong.');

report_unless()

report_unless 函式會在給定條件為 false 時使用 Exception Handler 來回報 Exception:

1report_unless($reportingDisabled, $e);
2 
3report_unless($reportingDisabled, 'Something went wrong.');
1report_unless($reportingDisabled, $e);
2 
3report_unless($reportingDisabled, 'Something went wrong.');

request()

request 函式回傳目前的 Request 實體,或是從目前 Request 中取得輸入欄位的值:

1$request = request();
2 
3$value = request('key', $default);
1$request = request();
2 
3$value = request('key', $default);

rescue()

rescue 函式會執行給定的閉包,並 Catch 在執行時發生的所有 Exception。被 Catch 到的 Exception 會被送到 Exception Handler,不過,Request 會繼續執行:

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

也可以傳入第二個引數給 rescue 函式。執行閉包時若有發生 Exception,就會使用這個引數來當作回傳的「預設」值:

1return rescue(function () {
2 return $this->method();
3}, false);
4 
5return rescue(function () {
6 return $this->method();
7}, function () {
8 return $this->failure();
9});
1return rescue(function () {
2 return $this->method();
3}, false);
4 
5return rescue(function () {
6 return $this->method();
7}, function () {
8 return $this->failure();
9});

resolve()

resolve 函式使用 Service Container 來將給定的類別或介面名稱解析為實體:

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

response()

response 函式建立一個 Response 實體,或是取得 Response Factory 的實體:

1return response('Hello World', 200, $headers);
2 
3return response()->json(['foo' => 'bar'], 200, $headers);
1return response('Hello World', 200, $headers);
2 
3return response()->json(['foo' => 'bar'], 200, $headers);

retry()

retry 函式會嘗試執行給定的閉包,直到達到最大嘗試次數限制。若該回呼未擲回(Throw) Exception,則會回傳該回呼的回傳值。若回呼擲回 Exception,就會自動嘗試重新執行回呼。達到最大嘗試次數後,就會擲回 Exception:

1return retry(5, function () {
2 // 嘗試 5 次,每次嘗試間暫停 100ms...
3}, 100);
1return retry(5, function () {
2 // 嘗試 5 次,每次嘗試間暫停 100ms...
3}, 100);

若想自動手動計算每次長時間要暫停的毫秒數,可傳入閉包作為第三個引數給 retry 函式:

1use Exception;
2 
3return retry(5, function () {
4 // ...
5}, function (int $attempt, Exception $exception) {
6 return $attempt * 100;
7});
1use Exception;
2 
3return retry(5, function () {
4 // ...
5}, function (int $attempt, Exception $exception) {
6 return $attempt * 100;
7});

為了方便起見,也可以提供陣列作為 retry 函式的第一個引數。會使用這個真累來判斷每次嘗試間要暫停多久:

1return retry([100, 200] function () {
2 // 第一次重試時休息 100ms,第二次重試時休息 200ms...
3});
1return retry([100, 200] function () {
2 // 第一次重試時休息 100ms,第二次重試時休息 200ms...
3});

若只想在特定條件下重試,可傳入一個閉包作為第四個引數給 retry 函式:

1use Exception;
2 
3return retry(5, function () {
4 // ...
5}, 100, function (Exception $exception) {
6 return $exception instanceof RetryException;
7});
1use Exception;
2 
3return retry(5, function () {
4 // ...
5}, 100, function (Exception $exception) {
6 return $exception instanceof RetryException;
7});

session()

session 函式可用來取得或設定 Session 值:

1$value = session('key');
1$value = session('key');

可以傳入一組索引鍵 / 值配對的陣列給該函式來賦值:

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

若未傳入任何值給該方法,則會回傳 Session Store 實體:

1$value = session()->get('key');
2 
3session()->put('key', $value);
1$value = session()->get('key');
2 
3session()->put('key', $value);

tap()

tap 方法接受兩個引數:任意值 $value、以及一個閉包。$value 會被傳入閉包中,然後 tap 方法會回傳 $value 的值。閉包的回傳值沒有任何影響:

1$user = tap(User::first(), function (User $user) {
2 $user->name = 'taylor';
3 
4 $user->save();
5});
1$user = tap(User::first(), function (User $user) {
2 $user->name = 'taylor';
3 
4 $user->save();
5});

若未傳入閉包給 tap 函式,則可呼叫任何給定 $value 上的方法。無論呼叫的方法回傳什麼值,在此處都會回傳 $value。舉例來說,Eloquent update 方法一般會回傳整數。不過,若我們可以將 update 方法的呼叫串在 tap 函式後方,來強制把該方法的回傳值改為 Model 實體:

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

若要將 tap 方法加到類別上,可以將 Illuminate\Support\Traits\Tappable Trait 加到類別中。該 Trait 的 tap 方法接受一個閉包作為其唯一的引數。物件實體本身會被傳入該閉包中,並由 tap 方法回傳:

1return $user->tap(function (User $user) {
2 // ...
3});
1return $user->tap(function (User $user) {
2 // ...
3});

throw_if()

throw_if 函式會在給定布林運算式取值為 true 時擲回一個 Exception:

1throw_if(! Auth::user()->isAdmin(), AuthorizationException::class);
2 
3throw_if(
4 ! Auth::user()->isAdmin(),
5 AuthorizationException::class,
6 'You are not allowed to access this page.'
7);
1throw_if(! Auth::user()->isAdmin(), AuthorizationException::class);
2 
3throw_if(
4 ! Auth::user()->isAdmin(),
5 AuthorizationException::class,
6 'You are not allowed to access this page.'
7);

throw_unless()

throw_unless 函式會在給定布林運算式取值為 false 時擲回一個 Exception:

1throw_unless(Auth::user()->isAdmin(), AuthorizationException::class);
2 
3throw_unless(
4 Auth::user()->isAdmin(),
5 AuthorizationException::class,
6 'You are not allowed to access this page.'
7);
1throw_unless(Auth::user()->isAdmin(), AuthorizationException::class);
2 
3throw_unless(
4 Auth::user()->isAdmin(),
5 AuthorizationException::class,
6 'You are not allowed to access this page.'
7);

today()

today 函式建立一個目前日期的新 Illuminate\Support\Carbon 實體:

1$today = today();
1$today = today();

trait_uses_recursive()

trait_uses_recursive 函式回傳該 Trait 使用的所有 Trait:

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

transform()

transform 函式會在給定值不為空白(Blank)時執行閉包,並回傳該閉包的回傳值:

1$callback = function (int $value) {
2 return $value * 2;
3};
4 
5$result = transform(5, $callback);
6 
7// 10
1$callback = function (int $value) {
2 return $value * 2;
3};
4 
5$result = transform(5, $callback);
6 
7// 10

可傳入預設值或閉包作為第三個引數給該函式。若給定值為空白時,會回傳這個值:

1$result = transform(null, $callback, 'The value is blank');
2 
3// The value is blank
1$result = transform(null, $callback, 'The value is blank');
2 
3// The value is blank

validator()

validator 函式使用給定的引數來建立一個新的 Validator 實體。可以用來當作是 Validator Facade 的替代:

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

value()

value 函式會回傳給定的值。不過,若傳入閉包給該函式,會執行該閉包並回傳該閉包的值:

1$result = value(true);
2 
3// true
4 
5$result = value(function () {
6 return false;
7});
8 
9// false
1$result = value(true);
2 
3// true
4 
5$result = value(function () {
6 return false;
7});
8 
9// false

也可以傳入更多引數給 value 函式。若第一個引數為閉包,則這些其他的引數會被作為引數來傳給該閉包。若不是閉包,則這些引數會被忽略:

1$result = value(function (string $name) {
2 return $name;
3}, 'Taylor');
4 
5// 'Taylor'
1$result = value(function (string $name) {
2 return $name;
3}, 'Taylor');
4 
5// 'Taylor'

view()

view 函式可取得一個 View 實體:

1return view('auth.login');
1return view('auth.login');

with()

with 函式會回傳給定的值。若有傳入閉包作為第二個引數該函式,會執行該閉包並回傳該閉包的回傳值:

1$callback = function (mixed $value) {
2 return is_numeric($value) ? $value * 2 : 0;
3};
4 
5$result = with(5, $callback);
6 
7// 10
8 
9$result = with(null, $callback);
10 
11// 0
12 
13$result = with(5, null);
14 
15// 5
1$callback = function (mixed $value) {
2 return is_numeric($value) ? $value * 2 : 0;
3};
4 
5$result = with(5, $callback);
6 
7// 10
8 
9$result = with(null, $callback);
10 
11// 0
12 
13$result = with(5, null);
14 
15// 5

其他公用程式

效能評定 (Benchmark)

有時候,我們會想快速地測試程式中某個部分的效能。這種時候,可以使用 Benchmark 輔助類別來測量完成給定回呼所需的毫秒數:

1<?php
2 
3use App\Models\User;
4use Illuminate\Support\Benchmark;
5 
6Benchmark::dd(fn () => User::find(1)); // 0.1 ms
7 
8Benchmark::dd([
9 'Scenario 1' => fn () => User::count(), // 0.5 ms
10 'Scenario 2' => fn () => User::all()->count(), // 20.0 ms
11]);
1<?php
2 
3use App\Models\User;
4use Illuminate\Support\Benchmark;
5 
6Benchmark::dd(fn () => User::find(1)); // 0.1 ms
7 
8Benchmark::dd([
9 'Scenario 1' => fn () => User::count(), // 0.5 ms
10 'Scenario 2' => fn () => User::all()->count(), // 20.0 ms
11]);

預設情況下,給定回呼擲回被執行一次 (即一次迭代),而執行所花費的時間會被顯示在瀏覽器或主控台上。

若想讓該回呼被執行多次,可使用該方法的第二個引數來指定該回呼要被呼叫的迭代數。執行該回呼超過一次時,Benchmark 類別會回傳在各個迭代間執行該回呼所花費的平均毫秒數:

1Benchmark::dd(fn () => User::count(), iterations: 10); // 0.5 ms
1Benchmark::dd(fn () => User::count(), iterations: 10); // 0.5 ms

Lottery

Laravel 的 Lottery 類別可用來依據給定的機率執行回呼。這個類別特別適用於想只在特定比例的連入 Request 內執行程式時:

1use Illuminate\Support\Lottery;
2 
3Lottery::odds(1, 20)
4 ->winner(fn () => $user->won())
5 ->loser(fn () => $user->lost())
6 ->choose();
1use Illuminate\Support\Lottery;
2 
3Lottery::odds(1, 20)
4 ->winner(fn () => $user->won())
5 ->loser(fn () => $user->lost())
6 ->choose();

也可以將 Laravel 的 Lottery 類別與其他 Laravel 功能組合使用。舉例來說,當資料庫查詢速度慢時,我們可以只將其中一部分的查詢回報給 Exception Handler。此外,由於 Lottery 類別是 callable,因此我們可以將 Lottery 實體傳給任何接受 callable 的方法:

1use Carbon\CarbonInterval;
2use Illuminate\Support\Facades\DB;
3use Illuminate\Support\Lottery;
4 
5DB::whenQueryingForLongerThan(
6 CarbonInterval::seconds(2),
7 Lottery::odds(1, 100)->winner(fn () => report('Querying > 2 seconds.')),
8);
1use Carbon\CarbonInterval;
2use Illuminate\Support\Facades\DB;
3use Illuminate\Support\Lottery;
4 
5DB::whenQueryingForLongerThan(
6 CarbonInterval::seconds(2),
7 Lottery::odds(1, 100)->winner(fn () => report('Querying > 2 seconds.')),
8);

測試 Lottery

Laravel 提供了一些簡單的方法,能讓你輕鬆測試專案的 Lottery 呼叫:

1// Lottery 結果永遠為「贏」...
2Lottery::alwaysWin();
3 
4// Lottery 結果永遠為「輸」...
5Lottery::alwaysLose();
6 
7// Lottery 的結果會先是「贏」,然後是「輸」,接著會回到其正常的行為...
8Lottery::fix([true, false]);
9 
10// Lottery 會回到正常行為...
11Lottery::determineResultsNormally();
1// Lottery 結果永遠為「贏」...
2Lottery::alwaysWin();
3 
4// Lottery 結果永遠為「輸」...
5Lottery::alwaysLose();
6 
7// Lottery 的結果會先是「贏」,然後是「輸」,接著會回到其正常的行為...
8Lottery::fix([true, false]);
9 
10// Lottery 會回到正常行為...
11Lottery::determineResultsNormally();
翻譯進度
100% 已翻譯
更新時間:
2024年6月30日 上午8:27:00 [世界標準時間]
翻譯人員:
  • cornch
幫我們翻譯此頁

留言

尚無留言

“Laravel” is a Trademark of Taylor Otwell.
The source documentation is released under MIT license. See laravel/docs on GitHub for details.
The translated documentations are released under MIT license. See cornch/laravel-docs-l10n on GitHub for details.