跳到主要內容

輔助函數

📝 此頁面為 Laravel 官方文檔的繁體中文翻譯。查看原始英文版本

輔助函數

簡介

Laravel 包含各種全域「輔助」PHP 函數。這些函數中有許多被框架本身使用;但是,如果您發現它們很方便,您可以自由地在自己的應用程式中使用它們。

可用方法

陣列和物件

數字

路徑

URL

雜項

陣列和物件

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

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

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

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

// true

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

// true

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

// false

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

// false

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

Arr::add 方法在給定的金鑰不存在於陣列中或設定為 null 時,將給定的金鑰/值對添加到陣列中:

use Illuminate\Support\Arr;

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

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

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

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

Arr::array() {.collection-method}

Arr::array 方法使用「點」語法從深層嵌套的陣列中檢索值(就像 Arr::get() 一樣),但如果請求的值不是 array,則會拋出 InvalidArgumentException

use Illuminate\Support\Arr;

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

$value = Arr::array($array, 'languages');

// ['PHP', 'Ruby']

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

// 拋出 InvalidArgumentException

Arr::boolean() {.collection-method}

Arr::boolean 方法使用「點」語法從深層嵌套的陣列中檢索值(就像 Arr::get() 一樣),但如果請求的值不是 boolean,則會拋出 InvalidArgumentException

use Illuminate\Support\Arr;

$array = ['name' => 'Joe', 'available' => true];

$value = Arr::boolean($array, 'available');

// true

$value = Arr::boolean($array, 'name');

// 拋出 InvalidArgumentException

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

Arr::collapse 方法將一個陣列的陣列或集合壓縮為單個陣列:

use Illuminate\Support\Arr;

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

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

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

Arr::crossJoin 方法交叉連接給定的陣列,返回一個包含所有可能排列的笛卡爾乘積:

use Illuminate\Support\Arr;

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

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

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

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

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

Arr::divide 方法返回兩個陣列:一個包含鍵,另一個包含給定陣列的值:

use Illuminate\Support\Arr;

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

// $keys: ['name']

// $values: ['Desk']

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

Arr::dot 方法將多維陣列展平為使用「點」語法表示深度的單層陣列:

use Illuminate\Support\Arr;

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

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

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

Arr::every() {.collection-method}

Arr::every 方法確保陣列中的所有值都通過給定的真值測試:

use Illuminate\Support\Arr;

$array = [1, 2, 3];

Arr::every($array, fn ($i) => $i > 0);

// true

Arr::every($array, fn ($i) => $i > 2);

// false

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

Arr::except 方法從陣列中移除給定的金鑰/值對:

use Illuminate\Support\Arr;

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

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

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

Arr::exceptValues() {.collection-method}

Arr::exceptValues 方法從陣列中移除指定的值:

use Illuminate\Support\Arr;

$array = ['foo', 'bar', 'baz', 'qux'];

$filtered = Arr::exceptValues($array, ['foo', 'baz']);

// ['bar', 'qux']

您還可以向 strict 參數傳遞 true,以便在過濾時使用嚴格類型比較:

use Illuminate\Support\Arr;

$array = [1, '1', 2, '2'];

$filtered = Arr::exceptValues($array, [1, 2], strict: true);

// ['1', '2']

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

Arr::exists 方法檢查給定的金鑰是否存在於提供的陣列中:

use Illuminate\Support\Arr;

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

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

// true

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

// false

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

Arr::first 方法返回通過給定真值測試的陣列的第一個元素:

use Illuminate\Support\Arr;

$array = [100, 200, 300];

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

// 200

預設值也可以作為方法的第三個參數傳遞。如果沒有值通過真值測試,將返回此值:

use Illuminate\Support\Arr;

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

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

Arr::flatten 方法將多維陣列展平為單層陣列:

use Illuminate\Support\Arr;

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

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

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

Arr::float() {.collection-method}

Arr::float 方法使用「點」語法從深層嵌套的陣列中檢索值(就像 Arr::get() 一樣),但如果請求的值不是 float,則會拋出 InvalidArgumentException

use Illuminate\Support\Arr;

$array = ['name' => 'Joe', 'balance' => 123.45];

$value = Arr::float($array, 'balance');

// 123.45

$value = Arr::float($array, 'name');

// 拋出 InvalidArgumentException

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

Arr::forget 方法使用「點」語法從深層嵌套的陣列中移除給定的金鑰/值對:

use Illuminate\Support\Arr;

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

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

// ['products' => []]

Arr::from() {.collection-method}

Arr::from 方法將各種輸入類型轉換為普通 PHP 陣列。它支援多種輸入類型,包括陣列、物件和一些常見的 Laravel 介面,例如 ArrayableEnumerableJsonableJsonSerializable。此外,它還處理 TraversableWeakMap 實例:

use Illuminate\Support\Arr;

Arr::from((object) ['foo' => 'bar']); // ['foo' => 'bar']

class TestJsonableObject implements Jsonable
{
    public function toJson($options = 0)
    {
        return json_encode(['foo' => 'bar']);
    }
}

Arr::from(new TestJsonableObject); // ['foo' => 'bar']

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

Arr::get 方法使用「點」語法從深層嵌套的陣列中檢索值:

use Illuminate\Support\Arr;

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

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

// 100

Arr::get 方法還接受一個預設值,如果陣列中不存在指定的金鑰,則返回此值:

use Illuminate\Support\Arr;

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

// 0

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

Arr::has 方法使用「點」語法檢查給定的項目或項目是否存在於陣列中:

use Illuminate\Support\Arr;

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

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

// true

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

// false

Arr::hasAll() {.collection-method}

Arr::hasAll 方法使用「點」語法判斷所有指定的金鑰是否存在於給定的陣列中:

use Illuminate\Support\Arr;

$array = ['name' => 'Taylor', 'language' => 'PHP'];

Arr::hasAll($array, ['name']); // true
Arr::hasAll($array, ['name', 'language']); // true
Arr::hasAll($array, ['name', 'IDE']); // false

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

Arr::hasAny 方法使用「點」語法檢查給定集合中的任何項目是否存在于陣列中:

use Illuminate\Support\Arr;

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

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

// true

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

// true

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

// false

Arr::integer() {.collection-method}

Arr::integer 方法使用「點」語法從深層嵌套的陣列中檢索值(就像 Arr::get() 一樣),但如果請求的值不是 int,則會拋出 InvalidArgumentException

use Illuminate\Support\Arr;

$array = ['name' => 'Joe', 'age' => 42];

$value = Arr::integer($array, 'age');

// 42

$value = Arr::integer($array, 'name');

// 拋出 InvalidArgumentException

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

Arr::isAssoc 方法在給定的陣列是關聯陣列時返回 true。如果陣列沒有從零開始的連續數字鍵,則被認為是「關聯的」:

use Illuminate\Support\Arr;

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

// true

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

// false

Arr::isList() {.collection-method}

Arr::isList 方法在給定的陣列的鍵是從零開始的連續整數時返回 true

use Illuminate\Support\Arr;

$isList = Arr::isList(['foo', 'bar', 'baz']);

// true

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

// false

Arr::join() {.collection-method}

Arr::join 方法使用字串連接陣列元素。使用此方法的第三個參數,您還可以指定陣列最後一個元素的連接字串:

use Illuminate\Support\Arr;

$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];

$joined = Arr::join($array, ', ');

// Tailwind, Alpine, Laravel, Livewire

$joined = Arr::join($array, ', ', ', and ');

// Tailwind, Alpine, Laravel, and Livewire

Arr::keyBy() {.collection-method}

Arr::keyBy 方法根據給定的鍵為陣列設定鍵。如果多個項目具有相同的鍵,則只有最後一個將出現在新陣列中:

use Illuminate\Support\Arr;

$array = [
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
];

$keyed = Arr::keyBy($array, 'product_id');

/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

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

Arr::last 方法返回通過給定真值測試的陣列的最後一個元素:

use Illuminate\Support\Arr;

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

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

// 400

預設值也可以作為方法的第三個參數傳遞。如果沒有值通過真值測試,將返回此值:

use Illuminate\Support\Arr;

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

Arr::map() {.collection-method}

Arr::map 方法遍歷陣列並將每個值傳遞給給定的回呼。陣列由回呼返回的值取代:

use Illuminate\Support\Arr;

$prices = [99, 249, 499];

$prices = Arr::map($prices, function ($price, $key) {
    return $price * ($key + 1);
});

// [99, 498, 1497]

Arr::mapSpread() {.collection-method}

Arr::mapSpread 方法遍歷陣列,將每個值展開作為回呼的參數。陣列由回呼返回的值取代:

use Illuminate\Support\Arr;

$half = Arr::mapSpread([100, 250, 125], function ($int) {
    return $int / 2;
});

// [50, 125, 62.5]

Arr::mapWithKeys() {.collection-method}

Arr::mapWithKeys 方法遍歷陣列並將每個值傳遞給給定的回呼。回呼返回的鍵值對將被添加到返回的陣列中:

use Illuminate\Support\Arr;

$array = [
    [
        'name' => 'Baked Potato',
        'type' => 'vegetable',
    ],
    [
        'name' => 'Burger',
        'type' => 'fastfood',
    ],
];

$result = Arr::mapWithKeys($array, function ($item, $key) {
    return [$item['name'] => $item['type']];
});

/*
    [
        'Baked Potato' => 'vegetable',
        'Burger' => 'fastfood',
    ]
*/

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

Arr::only 方法僅返回給定陣列中指定金鑰的鍵/值對:

use Illuminate\Support\Arr;

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

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

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

Arr::onlyValues() {.collection-method}

Arr::onlyValues 方法返回一個包含指定值的新陣列:

use Illuminate\Support\Arr;

$array = ['foo', 'bar', 'baz', 'qux'];

$filtered = Arr::onlyValues($array, ['foo', 'baz']);

// ['foo', 'baz']

Arr::partition() {.collection-method}

Arr::partition 方法根據真值回呼將陣列分割為兩個陣列:

use Illuminate\Support\Arr;

$packages = [
    ['name' => 'tailwindcss', 'type' => 'dev'],
    ['name' => 'laravel', 'type' => 'framework'],
    ['name' => 'pint', 'type' => 'dev'],
];

[$dev, $frameworks] = Arr::partition($packages, fn ($package) => $package['type'] === 'dev');

/*
    [
        [
            ['name' => 'tailwindcss', 'type' => 'dev'],
            ['name' => 'pint', 'type' => 'dev'],
        ],
        [
            ['name' => 'laravel', 'type' => 'framework'],
        ],
    ]
*/

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

Arr::pluck 方法從給定的陣列中檢索一列值:

use Illuminate\Support\Arr;

$users = [
    ['name' => 'Taylor', 'age' => 18],
    ['name' => 'Adam', 'age' => 15],
];

$names = Arr::pluck($users, 'name');

// ['Taylor', 'Adam']

您還可以使用「點」語法指定應提取的嵌套金鑰:

use Illuminate\Support\Arr;

$users = [
    ['first' => 'Taylor', 'last' => 'Otwell', 'device' => 'iPhone'],
    ['first' => 'Adam', 'last' => 'Wathan', 'device' => 'Android'],
];

$lastNames = Arr::pluck($users, 'last', 'first');

// ['Taylor' => 'Otwell', 'Adam' => 'Wathan']

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

Arr::prepend 方法將一個項目推送到陣列的開頭:

use Illuminate\Support\Arr;

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

$array = Arr::prepend($array, 0);

// [0, 1, 2, 3, 4]

如果需要,您可以指定要使用的金鑰:

use Illuminate\Support\Arr;

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

$array = Arr::prepend($array, 'Order', 'reference');

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

Arr::prependKeysWith() {.collection-method}

Arr::prependKeysWith 方法使用給定的前綴為給定陣列的所有鍵添加前綴:

use Illuminate\Support\Arr;

$array = ['name' => 'Joe', 'age' => 25];

$prefixed = Arr::prependKeysWith($array, 'data_');

// ['data_name' => 'Joe', 'data_age' => 25]

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

Arr::pull 方法從陣列中移除並返回給定金鑰的值:

use Illuminate\Support\Arr;

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

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

// $name: "Desk"

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

Arr::push() {.collection-method}

Arr::push 方法將一個項目追加到陣列的結尾:

use Illuminate\Support\Arr;

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

Arr::push($array, 5);

// [1, 2, 3, 4, 5]

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

Arr::query 方法將陣列轉換為 URL 查詢字串:

use Illuminate\Support\Arr;

$array = ['name' => 'Taylor', 'slide' => 13];

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

// "name=Taylor&slide=13"

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

Arr::random 方法從陣列中返回一個隨機元素:

use Illuminate\Support\Arr;

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

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

// 3 // (example output)

您可以將第二個參數傳遞給 random 方法,以指定您希望從陣列中檢索多少個隨機元素。如果第二個參數大於 1,則返回一組隨機元素:

use Illuminate\Support\Arr;

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

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

// [2, 4, 5] // (example output)

Arr::reject() {.collection-method}

Arr::reject 方法使用給定的回呼過濾陣列:

use Illuminate\Support\Arr;

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

$filtered = Arr::reject($array, function (int $value, int $key) {
    return $value > 250;
});

// [100, 200]

Arr::select() {.collection-method}

Arr::select 方法從陣列中選擇給定的鍵:

use Illuminate\Support\Arr;

$array = [
    ['name' => 'Taylor', 'age' => 18],
    ['name' => 'Adam', 'age' => 15],
];

$names = Arr::select($array, ['name']);

// [['name' => 'Taylor'], ['name' => 'Adam']]

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

Arr::set 方法使用「點」語法在深層嵌套的陣列中設定值:

use Illuminate\Support\Arr;

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

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

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

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

Arr::shuffle 方法隨機打亂陣列:

use Illuminate\Support\Arr;

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

$shuffled = Arr::shuffle($array);

// [3, 1, 5, 2, 4] // (example output)

Arr::sole() {.collection-method}

Arr::sole 方法返回陣列中匹配給定真值測試的第一個元素,但如果找到的元素不是一個,則會拋出異常:

use Illuminate\Support\Arr;

$array = [100, 200, 300];

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

// 200

Arr::some() {.collection-method}

Arr::some 方法驗證陣列中是否有一個元素通過給定的真值測試:

use Illuminate\Support\Arr;

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

Arr::some($array, function ($value, $key) {
    return $value > 5;
});

// false

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

Arr::sort 方法按值對陣列進行排序:

use Illuminate\Support\Arr;

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

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

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

您可以使用自己的比較函數按金鑰對陣列進行排序:

use Illuminate\Support\Arr;

$array = ['key_1' => 'Desk', 'key_2' => 'Table', 'key_3' => 'Chair'];

$sorted = Arr::sort($array, function ($a, $b) {
    return strcasecmp($a, $b);
});

// ['key_1' => 'Chair', 'key_2' => 'Desk', 'key_3' => 'Table']

Arr::sortDesc() {.collection-method}

Arr::sortDesc 方法按值對陣列進行降序排序:

use Illuminate\Support\Arr;

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

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

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

您可以使用自己的比較函數按金鑰對陣列進行降序排序:

use Illuminate\Support\Arr;

$array = ['key_1' => 'Desk', 'key_2' => 'Table', 'key_3' => 'Chair'];

$sorted = Arr::sortDesc($array, function ($a, $b) {
    return strcasecmp($a, $b);
});

// ['key_3' => 'Table', 'key_1' => 'Desk', 'key_2' => 'Chair']

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

Arr::sortRecursive 方法使用 usort 函數遞歸地對陣列進行排序:

use Illuminate\Support\Arr;

$array = [
    ['Charlie', 2],
    ['Alice', 1],
    ['Bob', 3],
];

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

// [
//     ['Alice', 1],
//     ['Bob', 3],
//     ['Charlie', 2],
// ]

Arr::string() {.collection-method}

Arr::string 方法使用「點」語法從深層嵌套的陣列中檢索值(就像 Arr::get() 一樣),但如果請求的值不是 string,則會拋出 InvalidArgumentException

use Illuminate\Support\Arr;

$array = ['name' => 'Joe', 'age' => 42];

$value = Arr::string($array, 'name');

// Joe

$value = Arr::string($array, 'age');

// 拋出 InvalidArgumentException

Arr::take() {.collection-method}

Arr::take 方法從陣列中返回指定數量的元素:

use Illuminate\Support\Arr;

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

$chunk = Arr::take($array, 3);

// [0, 1, 2]

$chunk = Arr::take($array, -2);

// [4, 5]

Arr::toCssClasses() {.collection-method}

Arr::toCssClasses 方法接受一個 CSS 類別的陣列,其中鍵包含您希望添加的 CSS 類別或類別,而值包含布林表達式。如果表達式評估為 true,則將添加鍵中包含的 CSS 類別。如果陣列包含數字鍵,則始終會將該元素包含在返回的類別列表中:

use Illuminate\Support\Arr;

$array = [
    'p-4',
    'font-bold' => $isActive,
    'text-gray-500' => ! $isActive,
    'bg-red' => $hasError,
];

$classes = Arr::toCssClasses($array);

/*
    [
        'p-4',
        'font-bold',
        'bg-red',
    ]
*/

Arr::toCssStyles() {.collection-method}

Arr::toCssStyles 方法接受一個 CSS 樣式的陣列,其中鍵包含您希望添加的 CSS 屬性或樣式,而值包含布林表達式。如果表達式評估為 true,則將添加鍵中包含的 CSS 樣式。如果陣列包含數字鍵,則始終會將該元素包含在返回的樣式列表中:

use Illuminate\Support\Arr;

$array = [
    'background-color: red',
    'font-weight: bold' => $isActive,
];

$styles = Arr::toCssStyles($array);

/*
    [
        'background-color: red',
        'font-weight: bold',
    ]
*/

Arr::undot() {.collection-method}

Arr::undot 方法使用「點」語法將一維陣列展開到多維陣列中:

use Illuminate\Support\Arr;

$array = [
    'user.name' => 'Kevin',
    'user.age' => 25,
    'user.posts.post_1' => 'Title 1',
    'user.posts.post_2' => 'Title 2',
];

$undotted = Arr::undot($array);

// [
//     'user' => [
//         'name' => 'Kevin',
//         'age' => 25,
//         'posts' => [
//             'post_1' => 'Title 1',
//             'post_2' => 'Title 2',
//         ],
//     ],
// ]

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

Arr::where 方法使用給定的回呼過濾陣列:

use Illuminate\Support\Arr;

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

$filtered = Arr::where($array, function (string|int $value) {
    return is_int($value);
});

// [100, 300, 500]

Arr::whereNotNull() {.collection-method}

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

use Illuminate\Support\Arr;

$array = [0, null, 1, 2, null];

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

// [0, 1, 2]

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

Arr::wrap 方法將給定的值包裝在陣列中,如果它還不是陣列的話:

use Illuminate\Support\Arr;

$string = 'Laravel'

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

// ['Laravel']

如果給定的值已經是一個陣列,Arr::wrap 方法將不會將其包裝在陣列中:

use Illuminate\Support\Arr;

$array = ['Laravel'];

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

// ['Laravel']

如果給定的值是 nullArr::wrap 方法將返回一個空陣列:

use Illuminate\Support\Arr;

$array = Arr::wrap(null);

// []

data_fill() {.collection-method .first-collection-method}

data_fill 方法使用「點」語法使用給定的值填充陣列中缺失的值:

$data = ['flowers' => []];

data_fill($data, 'flowers.0.name', ['name' => 'Daylily']);

// ['flowers' => [['name' => 'Daylily']]]

data_fill($data, 'flowers.1.name', 'Spider Lily');

// ['flowers' => [['name' => 'Daylily'], ['name' => 'Spider Lily']]

data_fill 方法還接受一個 Closure 作為第三個參數,以便有條件地填充陣列:

$data = ['users' => [
    ['name' => 'Taylor', 'email' => '[email protected]'],
    ['name' => 'Abigail', 'email' => '[email protected]'],
]];

data_fill($data, 'users.*.active', function ($user) {
    return $user['name'] === 'Taylor';
});

/*
    [
        ['name' => 'Taylor', 'email' => '[email protected]', 'active' => true],
        ['name' => 'Abigail', 'email' => '[email protected]', 'active' => false],
    ]
*/

data_get() {.collection-method}

data_get 方法使用「點」語法從嵌套的陣列或物件中檢索值:

$data = ['names' => ['john' => ['contacts' => ['phone' => '555-1234']]]];

$name = data_get($data, 'names.john.contacts.phone');

// 555-1234

如果在資料結構中未找到金鑰,也可以使用預設值:

$data = ['names' => ['john' => ['contacts' => ['phone' => '555-1234']]]];

$name = data_get($data, 'names.john.contacts.office', 'default');

// default

data_set() {.collection-method}

data_set 方法使用「點」語法在嵌套的陣列或物件中設定值:

$data = ['names' => ['john' => ['contacts' => ['phone' => '555-1234']]]];

data_set($data, 'names.john.contacts.office', '555-5678');

// $data is now ['names' => ['john' => ['contacts' => ['phone' => '555-1234', 'office' => '555-5678']]]]

data_set 方法還接受一個 Closure 作為第三個參數,以便有條件地設定值:

$data = ['names' => [
    ['name' => 'Taylor', 'email' => '[email protected]'],
    ['name' => 'Abigail', 'email' => '[email protected]'],
]];

data_set($data, 'users.*.active', function ($user) {
    return $user['name'] === 'Taylor';
});

/*
    [
        ['name' => 'Taylor', 'email' => '[email protected]', 'active' => true],
        ['name' => 'Abigail', 'email' => '[email protected]', 'active' => false],
    ]
*/

data_forget() {.collection-method}

data_forget 方法使用「點」語法從嵌套的陣列或物件中移除一個值:

$data = ['names' => ['john' => ['contacts' => ['phone' => '555-1234']]]];

data_forget($data, 'names.john.contacts.phone');

// $data is now ['names' => ['john' => ['contacts' => []]]]

head() {.collection-method .first-collection-method}

head 方法返回陣列中的第一個元素:

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

$first = head($array);

// 1

last() {.collection-method}

last 方法返回陣列中的最後一個元素:

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

$last = last($array);

// 4

字串

Str::after() {.collection-method .first-collection-method}

Str::after 方法返回在給定的子字串之後的所有內容:

use Illuminate\Support\Str;

$sentence = 'The quick brown fox jumps over the lazy dog.';

$substring = Str::after($sentence, 'fox');

// "jumps over the lazy dog."

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

Str::afterLast 方法返回在給定的子字串之後的所有內容,包括子字串:

use Illuminate\Support\Str;

$sentence = 'The quick brown fox jumps over the lazy dog.';

$substring = Str::afterLast($sentence, 'fox');

// " jumps over the lazy dog."

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

Str::before 方法返回在給定的子字串之前的所有內容:

use Illuminate\Support\Str;

$sentence = 'The quick brown fox jumps over the lazy dog.';

$substring = Str::before($sentence, 'fox');

// "The quick brown "

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

Str::beforeLast 方法返回在給定的子字串之前的所有內容,包括子字串:

use Illuminate\Support\Str;

$sentence = 'The quick brown fox jumps over the lazy dog.';

$substring = Str::beforeLast($sentence, 'fox');

// "The quick brown fox"

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

Str::between 方法返回在兩個給定的子字串之間的所有內容:

use Illuminate\Support\Str;

$sentence = 'The quick brown fox jumps over the lazy dog.';

$substring = Str::between($sentence, 'quick', 'fox');

// "quick brown "

Str::betweenFirst() {.collection-method}

Str::betweenFirst 方法返回在兩個給定的子字串之間的第一個匹配:

use Illuminate\Support\Str;

$sentence = '[a] ab [b] bc [c]';

$substring = Str::betweenFirst($sentence, '[', ']');

// "a"

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

Str::camel 方法將給定的字串轉換為駝峰命名法:

use Illuminate\Support\Str;

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

// fooBar

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

Str::contains 方法判斷給定的字串是否包含另一個子字串:

use Illuminate\Support\Str;

$contains = Str::contains('This is a foo bar string.', ['foo', 'bar']);

// true

$contains = Str::contains('This is a foo bar string.', ['baz', 'qux']);

// false

您還可以將 ignoreCase 參數傳遞給 contains 方法,以忽略大小寫:

use Illuminate\Support\Str;

$contains = Str::contains('This is a foo bar string.', 'FOO', ignoreCase: true);

// true

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

Str::containsAll 方法判斷給定的字串是否包含所有給定的子字串:

use Illuminate\Support\Str;

$contains = Str::containsAll('This is a foo bar string.', ['foo', 'bar']);

// true

$contains = Str::containsAll('This is a foo bar string.', ['baz', 'qux']);

// false

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

Str::endsWith 方法判斷給定的字串是否以另一個子字串結尾:

use Illuminate\Support\Str;

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

// true

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

// true

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

// false

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

Str::limit 方法將字串截斷為給定的最大長度。此方法將在字串的末尾附加 ...

use Illuminate\Support\Str;

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

// "The quick brown fox..."

您也可以將第三個參數傳遞給 limit 方法以更改將附加到截斷字串末尾的字串:

use Illuminate\Support\Str;

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

// "The quick brown fox>>>"

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

orderedUuid 方法生成一個可排序的 UUIDv7 實例。此 UUID 對於索引資料庫儲存非常有效,因為它們可以按字典順序排序:

use Illuminate\Support\Str;

(Str::orderedUuid())->toString(); // "01925262-c6ca-7c8a-a00c-078378149ad9"

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

Str::plural 方法將字串從單數轉換為複數。Laravel 的pluralizer基於 ramsey/inflect 包,支援多種語言:

use Illuminate\Support\Str;

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

// cars

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

// children

您可以將第二個參數傳遞給 plural 方法以指定複數形式的數量:

use Illuminate\Support\Str;

$plural = Str::plural('apple', 0);

// apples

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

// apple

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

// apples

Str::pluralStudly() {.collection-method}

Str::pluralStudly 方法使用大寫蛇形命名法將字串從單數轉換為複數:

use Illuminate\Support\Str;

$plural = Str::pluralStudly('has_time');

// has_times

$plural = Str::pluralStudly('has_thought');

// has_thoughts

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

Str::random 方法生成一個給定長度的隨機字串:

use Illuminate\Support\Str;

$random = Str::random(40);

// "vAnT8S8FVWd9z6Z8Xf8u3b1s9a2c4e5f6g7h8"

如果沒有指定,此方法預設使用字母和數字。此外,您可以使用 alphabet 方法指定要使用的字元集:

use Illuminate\Support\Str;

$random = Str::random(40, 'alpha');

// "aBcDeFgHiJkLmNoPqRsTuVwXyZaBcDeFgHiJk"

$random = Str::random(40, 'alphaNum');

// "vAnT8S8FVWd9z6Z8Xf8u3b1s9a2c4e5f6g7h8"

$random = Str::random(40, 'ascii');

// "F@1t!gHj#KlPqRsTuVwXyZaBcDeFgHiJkLm"

$random = Str::random(40, 'unprintable');

// "\x1e\x8e\x9a\x1b\x08\x14\x12\x1c\x01\x03\x0e\x09\x17\x05\x16\x0b\x19\x1a\x0d\x10\x06\x12\x04\x1e\x11\x0f\x1c\x13\x0c\x07\x0a\x1d\x18\x1f\x02\x19\x09\x0b\x15\x0e"

Str::remove() {.collection-method}

Str::remove 方法從字串中移除一個子字串:

use Illuminate\Support\Str;

$string = Str::remove('Peter Piper picked a peck of pickled peppers.', ['pecker', 'pickled', 'piper']);

// "Peter Piper picked a peck of peppers."

您還可以使用第三個參數來忽略大小寫:

use Illuminate\Support\Str;

$string = Str::remove('PETER PIPER PICKED A PECK OF PICKLED PEPPERS.', ['pecker', 'pickled', 'piper'], ignoreCase: true);

// "PETER PIPER PICKED A PECK OF PEPPERS."

Str::repeat() {.collection-method}

Str::repeat 方法重複給定的字串給定的次數:

use Illuminate\Support\Str;

$repeated = Str::repeat('abc', 3);

// "abcabcabc"

Str::replace() {.collection-method}

Str::replace 方法替換給定的字串中的一個子字串:

use Illuminate\Support\Str;

$string = Str::replace('foo is the best?', 'bar', 'best');

// "foo is the bar?"

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

Str::replaceArray 方法使用陣列中的值按順序替換給定字串中的佔位符:

use Illuminate\Support\Str;

$string = 'The event will take place on :first and :second';

$formatted = Str::replaceArray($string, [':first', ':second'], ['November', 'December']);

// "The event will take place on November and December"

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

Str::replaceFirst 方法替換給定字串中子字串的第一次出現:

use Illuminate\Support\Str;

$string = 'The quick brown fox jumps over the lazy dog.';

$formatted = Str::replaceFirst($string, 'the', 'a');

// "A quick brown fox jumps over the lazy dog."

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

Str::replaceLast 方法替換給定字串中子字串的最後一次出現:

use Illuminate\Support\Str;

$string = 'The quick brown fox jumps over the lazy dog.';

$formatted = Str::replaceLast($string, 'the', 'a');

// "The quick brown fox jumps over a lazy dog."

Str::start() {.collection-method}

Str::start 方法在字串的開頭添加給定的值,如果它尚未以給定的值開頭:

use Illuminate\Support\Str;

$adjusted = Str::start($string, 'this-is-a-');

$adjusted = Str::start('this-is-a-string', 'this-is-a-');

// this-is-a-string

$adjusted = Str::start('awesome-string', 'this-is-a-');

// this-is-a-awesome-string

Str::startsWith() {.collection-method}

Str::startsWith 方法判斷給定的字串是否以另一個子字串開頭:

use Illuminate\Support\Str;

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

// true

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

// true

$result = Str::startsWith('This is my name', ['that', 'there']);

// false

Str::studly() {.collection-method}

Str::studly 方法將給定的字串轉換為大寫蛇形命名法:

use Illuminate\Support\Str;

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

// FooBar

Str::substr() {.collection-method}

Str::substr 方法返回字串的給定部分:

use Illuminate\Support\Str;

$string = 'Laravel 13';

$sub = Str::substr($string, 0, 6);

// "Laravel"

Str::substrCount() {.collection-method}

Str::substrCount 方法返回給定的子字串在字串中出現的次數:

use Illuminate\Support\Str;

$count = Str::substrCount('This is a test, test.', 'test');

// 2

Str::text() {.collection-method}

Str::text 方法返回一個包含字串給定部分的 Stringable 實例:

use Illuminate\Support\Str;

$string = Str::text('The quick brown fox jumps over the lazy dog.')->after('fox')->before('lazy');

// "jumps over the "

Str::title() {.collection-method}

Str::title 方法將給定的字串轉換為標題大小寫:

use Illuminate\Support\Str;

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

// "A Nice Title Uses The Correct Case"

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

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

use Illuminate\Support\Str;

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

// "LARAVEL"

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

uuid 方法生成一個 UUIDv4(隨機)實例:

use Illuminate\Support\Str;

(Str::uuid())->toString(); // "5b9e3467-2c4f-4d5a-b9b5-4f6f7f8f9d0a"

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

Str::words 方法返回字串中的給定數量的單詞:

use Illuminate\Support\Str;

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

// "Perfectly balanced, as"

您可以選擇將第三個參數傳遞給 words 方法,該參數將附加到字串的末尾:

use Illuminate\Support\Str;

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

// "Perfectly balanced, as>>>"

Str::wrap() {.collection-method}

Str::wrap 方法將字串包裹在給定的字串中,如果尚未包裝:

use Illuminate\Support\Str;

Str::wrap('Laravel', '');

// "Laravel"

Str::wrap('Laravel', 'html');

// "htmlLaravelhtml"

Str::wrap('Laravel', '''');

// "'Laravel'"

URL

action() {.collection-method .first-collection-method}

action 方法生成一個給定控制器動作的 URL:

use App\Http\Controllers\HomeController;

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

asset() {.collection-method}

asset 方法生成一個資源的 URL:

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

您可以將第二個參數傳遞給 asset 方法以指定所生成 URL 的協議:

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

$url = asset('img/photo.jpg', true); // https://example.com/img/photo.jpg

route() {.collection-method}

route 方法生成一個給定具名路由的 URL:

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

如果給定的路由需要參數,這些參數可以作為第二個參數傳遞給 route 方法:

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

您還可以傳遞 true 作為第三個參數以強制生成 HTTPS URL:

$url = route('route.name', [], true);

secure_asset() {.collection-method}

secure_asset 方法使用 HTTPS 協議生成資源的 URL:

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

secure_url() {.collection-method}

secure_url 方法使用 HTTPS 協議生成給定路徑的完整 URL:

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

to_action() {.collection-method}

to_action 方法生成一個給定控制器動作的 URL:

use App\Http\Controllers\HomeController;

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

to_route() {.collection-method}

to_route 方法生成一個給定具名路由的 URL:

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

如果給定的路由需要參數,這些參數可以作為第二個參數傳遞給 to_route 方法:

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

您還可以傳遞 true 作為第三個參數以強制生成 HTTPS URL:

$url = to_route('route.name', [], true);

url() {.collection-method}

url 方法生成給定路徑的完整 URL:

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

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

如果未提供路徑,將返回應用程式的根 URL:

$url = url();

雜項

abort() {.collection-method .first-collection-method}

abort 方法中斷具有給定 HTTP 狀態碼的請求:

abort(404);

您還可以提供自訂回應的文字:

abort(403, 'Unauthorized.');

abort_if() {.collection-method}

abort_if 方法在給定的布林條件為 true 時中斷具有給定 HTTP 狀態碼的請求:

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

abort_unless() {.collection-method}

abort_unless 方法在給定的布林條件為 false 時中斷具有給定 HTTP 狀態碼的請求:

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

app() {.collection-method}

app 方法返回服務容器的實例:

$container = app();

您可以選擇傳遞類別名以綁定到容器中。此方法將返回綁定的實例:

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

auth() {.collection-method}

auth 方法返回身份驗證器的實例。您也可以使用它作為 Auth facade 的快捷方式:

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

如果需要,您可以指定要使用的守衛實例:

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

back() {.collection-method}

back 方法將使用者重定向到上一個位置:

Route::post('/user/profile', function () {
    // 更新使用者的設定檔...

    return back()->with('status', 'Profile updated!');
});

bcrypt() {.collection-method}

bcrypt 方法使用 Bcrypt 雜湊給定的值。您可以將此方法用作 Hash facade 的快捷方式:

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

blank() {.collection-method}

blank 方法判斷給定的值是否為「空」:

blank(null); // true

blank(''); // true

blank([]); // true

blank('Hello'); // false

blank([1, 2, 3]); // false

要使用 blank 方法的逆邏輯,請使用 filled 方法。

broadcast() {.collection-method}

broadcast 方法透過廣播通道廣播給定的事件:

broadcast(new UserStatusUpdated($user));

broadcast_if() {.collection-method}

broadcast_if 方法在給定的布林條件為 true 時透過廣播通道廣播給定的事件:

broadcast_if($user->isActive(), new UserStatusUpdated($user));

broadcast_unless() {.collection-method}

broadcast_unless 方法在給定的布林條件為 false 時透過廣播通道廣播給定的事件:

broadcast_unless($user->isInactive(), new UserStatusUpdated($user));

cache() {.collection-method}

cache 方法可透過快取存取各種快取功能:

$value = cache('key');

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

cache()->put('key', 'value', 300);

class_uses_recursive() {.collection-method}

class_uses_recursive 方法返回一個類別使用的 trait(包括其父類別)的陣列:

$traits = class_uses_recursive(SuperClass::class);

collect() {.collection-method}

collect 方法從給定的值建立一個集合實例:

$collection = collect(['name' => 'Taylor', 'age' => 18]);

config() {.collection-method}

config 方法可存取配置值:

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

config([&39;app.timezone' => 'UTC']);

如果配置不存在,您可以傳遞第二個參數作為預設值:

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

context() {.collection-method}

context 方法可存取上下文值:

$value = context('key');

context([&39;key' => 'value']);

如果上下文值不存在,您可以傳遞第二個參數作為預設值:

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

cookie() {.collection-method}

cookie 方法可建立一個新的Cookie 實例:

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

csrf_field() {.collection-method}

csrf_field 方法生成一個 CSRF 欄位的 HTML 欄位:

{{ csrf_field() }}

csrf_token() {.collection-method}

csrf_token 方法返回當前 CSRF 令牌的值:

$token = csrf_token();

decrypt() {.collection-method}

decrypt 方法解密給定的值:

$decrypted = decrypt($encryptedValue);

dd() {.collection-method}

dd 方法轉儲給定的變數並終止腳本的執行:

dd($value);

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

如果您不想停止腳本的執行,請改用 dump 方法。

dispatch() {.collection-method}

dispatch 方法將任務排入佇列:

dispatch(new SendPodcastEmail($podcast));

dispatch_sync() {.collection-method}

dispatch_sync 方法將任務同步排入佇列:

dispatch_sync(new SendPodcastEmail($podcast));

dump() {.collection-method}

dump 方法轉儲給定的變數:

dump($value);

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

encrypt() {.collection-method}

encrypt 方法加密給定的值:

$encrypted = encrypt($secret);

env() {.collection-method}

env 方法检索環境變數值或返回預設值:

$env = env('APP_ENV');

$env = env('APP_ENV', 'production');

event() {.collection-method}

event 方法派發一個事件給其所有的監聽器:

event(new PodWasPlayed($podcast));

event([new PodWasPlayed($podcast), new PodWasDownloaded($podcast)]);

filled() {.collection-method}

filled 方法判斷給定的值是否不是「空」:

filled(0); // true

filled(''); // false

filled([]); // false

filled(null); // false

要使用 filled 方法的逆邏輯,請使用 blank 方法。

info() {.collection-method}

info 方法寫入一條資訊級別的日誌消息:

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

literal() {.collection-method}

literal 方法返回一個新的 Illuminate\Support\Literal 實例。此實例可以用作陣列鍵或 Eloquent 模型屬性,以指示值不應被字元轉義:

use Illuminate\Support\Literal;

$data = [
    Literal::string('\SomeRawHtml') => '<b>Note</b>: All is fair in love and war.',
];

logger() {.collection-method}

logger 方法可寫入一條偵錯級別的日誌消息:

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

如果沒有提供參數,它將返回日誌通道的實例:

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

method_field() {.collection-method}

method_field 方法生成一個 HTML 隱藏輸入欄位。這在表單中使用 PUTPATCHDELETE 方法時非常有用:

{{ method_field('PUT') }}

now() {.collection-method}

now 方法返回當前時間的 Illuminate\Support\Carbon 實例:

$now = now();

old() {.collection-method}

old 方法檢索session中的上次輸入值:

$username = old('username');

您還可以傳遞一個預設值作為方法的第二個參數。如果session中不存在該值,將返回此值:

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

once() {.collection-method}

once 方法執行給定的閉包,但僅執行一次。對此方法的任何後續調用都將返回第一次執行期間返回的值:

function doSomething()
{
    return once(function () {
        return 'This will only run once';
    });
}

doSomething(); // This will only run once

doSomething(); // This will only run once

optional() {.collection-method}

optional 方法接受任何參數並允許您使用「鏈式」語法來存取物件上的屬性或調用方法。如果給定的物件是 null,則屬性和方法將返回 null 而不是拋出異常:

use Illuminate\Support\Optional;

$user = User::find(1);

$name = optional($user)->name;

// "Taylor"

如果給定的值不是 null,則 optional 函數的結果將是給定值本身:

use Illuminate\Support\Optional;

$user = User::find(1);

$name = optional($user)->name ?? 'Taylor';

// "Taylor"

您也可以將閉包作為 optional 函數的第二個參數傳遞。如果閉包返回的值不是 null,則將執行該閉包:

use Illuminate\Support\Optional;

$result = optional(fn () => resolve('App\Models\User'))->admin;

// null

policy() {.collection-method}

policy 方法獲取給定模型類別的策略實例:

$policy = policy(User::class);

redirect() {.collection-method}

redirect 方法返回一個重定向響應的實例:

return redirect('/home/dashboard');

return redirect()->route('dashboard');

如果需要,您可以傳遞 true 作為第三個參數以強制生成 HTTPS URL:

return redirect()->route('dashboard', [], true);

您可以使用 to_route 方法作為 redirect 方法的替代:

return to_route('dashboard');

report() {.collection-method}

report 方法向您異常報告服務中的一個異常:

report($e);

report_if() {.collection-method}

report_if 方法在給定的布林條件為 true 時向您異常報告服務中的一個異常

report_if($this->isDown(), new AppDownException);

report_unless() {.collection-method}

report_unless 方法在給定的布林條件為 false 時向您異常報告服務中的一個異常

report_unless(Auth::user()->isAdmin(), new AppDownException);

request() {.collection-method}

request 方法返回當前HTTP 請求的實例或獲取輸入值:

$request = request();

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

rescue() {.collection-method}

rescue 方法在給定的回呼中捕獲異常並透過異常報告服務進行報告。您可以選擇提供將作為異常報告的第二個參數或 false 以完全不報告異常:

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

您可以將第三個參數作為預設值傳遞給 rescue 方法。如果發生異常,將返回此值:

return rescue(function () {
    return $this->doSomething();
}, false, fn () => $this->defaultOperation());

resolve() {.collection-method}

resolve 方法從容器中解析一個類別或介面名以獲取其實例:

$api = resolve('App\Services\Stripe');

response() {.collection-method}

response 方法建立一個響應的實例或獲取當前響應的實例:

return response('Hello World', 200, ['Content-Type' => 'text/plain']);

return response()->json(['name' => 'Steve', 'state' => 'CA'], 200);

retry() {.collection-method}

retry 方法在給定的回呼失敗時重複執行給定的回呼:

return retry(5, function () {
    // 嘗試五次,如果失敗則拋出異常...
}, 100);

session() {.collection-method}

session 方法可存取 session值:

$value = session('key');

您可以將陣列傳遞給 session 方法以設定多個 session值:

session([&39;chairs' => 7, 'instructors' => 5]);

tap() {.collection-method}

tap 方法將給定的值傳遞給給定的回呼並返回該值。回呼可以對值執行任何操作而無需修改值本身:

use Illuminate\Support\User;

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

    $user->save();
});

如果沒有傳遞回呼,您可以調用任何方法。每個方法調用將返回 tap 方法的實例,因此您可以將方法調用鏈接在一起:

use Illuminate\Support\User;

$user = tap(User::first())
    ->save()
    ->fill(['active' => true]);

throw_if() {.collection-method}

throw_if 方法在給定的布林條件為 true 時拋出異常

throw_if($this->isDown(), AppDownException::class);

throw_if(
    $this->user()->isNot($post->author),
    AuthorizationException::class
);

throw_unless() {.collection-method}

throw_unless 方法在給定的布林條件為 false 時拋出異常

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

throw_unless(
    $this->user()->can('edit-post', $post),
    [AuthorizationException::class, 'Not authorized.']
);

today() {.collection-method}

today 方法返回當前日期的 Illuminate\Support\Carbon 實例:

$today = today();

trait_uses_recursive() {.collection-method}

trait_uses_recursive 方法返回一個 trait(包括其父 trait)的陣列:

$traits = trait_uses_recursive(SuperTrait::class);

transform() {.collection-method}

transform 方法根據給定的回呼在集合或陣列上執行映射和/或過濾操作:

$collection = collect(['name' => 'John', 'age' => 17]);

$collection = transform($collection, function ($user, $key) {
    if ($user['age'] >= 18) {
        $user['status'] = 'adult';
    }

    return $user;
});

/*
    [
        'name' => 'John',
        'age' => 17,
        'status' => 'adult',
    ]
*/

如果給定的值不是陣列或集合,transform 方法將返回 null

transform('string', function ($value) {
    return $value;
});

validator() {.collection-method}

validator 方法可建立一個新的驗證器實例:

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

value() {.collection-method}

value 方法返回給定的值。如果值是閉包,則返回閉包的結果:

$result = value(function () {
    return 'hello';
});

// hello

view() {.collection-method}

view 方法建立一個視圖響應的實例:

return view('welcome');

with() {.collection-method}

with 方法返回給定的值。如果值是閉包,則返回閉包的結果:

$result = with(function () {
    return 'hello';
}, function ($value) {
    return strtoupper($value);
});

// HELLO

when() {.collection-method}

when 方法在給定的布林條件為 true 時對給定的值執行給定的回呼:

$collection = collect([1, 2, 3]);

$collection = $collection->when(true, function ($collection, $value) {
    return $collection->push(4);
});

// [1, 2, 3, 4]

如果未傳遞回呼,則 when 方法將在布林條件為 true 時返回給定的值:

$collection = collect([1, 2, 3]);

$collection = $collection->when(true);

// [1, 2, 3, 4]

其他實用工具

效能基準測試

Laravel 的 benchmark 函數允許您快速衡量給定回呼的執行時間:

use Illuminate\Support\Benchmark;

Benchmark::dd(fn () => Task::all()); // 10ms (example)

Benchmark::dd([
    'Task::all' => fn () => Task::all(),
    'Task::active' => fn () => Task::active(),
    'Task::incomplete' => fn () => Task::incomplete(),
]); // Task::all: 10ms (example), Task::active: 5ms (example), Task::incomplete: 3ms (example)

如果您只想以秒為單位回傳執行時間(作為 float),您可以將 $callback 參數傳遞給 Benchmark::measure 方法:

$executionTime = Benchmark::measure(fn () => Task::all());

如果您想重複執行基準測試多次以獲得更一致的結果,您可以將第二個參數傳遞給 Benchmark::measure 方法或將 $iterations 參數傳遞給 Benchmark::dd 方法:

$executionTime = Benchmark::measure(fn () => Task::all(), 100);

Benchmark::dd(fn () => Task::all(), 100);

日期和時間

Laravel 包含各種方便存取和操作日期的輔助函數。這些輔助函數基於 Carbon 類別,後者繼承自 PHP 的 DateTime 類別。

carbon() {.collection-method .first-collection-method}

carbon 方法建立一個 Carbon 實例以允許流暢的日期操作:

$date = carbon('2025-07-10');

$date = carbon()->addHours(4);

$date = now()->addWeekdays(3);

today() {.collection-method}

today 方法返回當前時間的 Illuminate\Support\Carbon 實例:

$today = today();

tomorrow() {.collection-method}

tomorrow 方法返回明天的 Illuminate\Support\Carbon 實例:

$tomorrow = tomorrow();

yesterday() {.collection-method}

yesterday 方法返回昨天的 Illuminate\Support\Carbon 實例:

$yesterday = yesterday();

延遲函數

延遲函數允許您將操作推遲到 HTTP 響應發送給使用者之後。這減少了處理時間,因為使用者在任何延遲函數完成之前收到響應。延遲函數透過 defer 輔助函數定義,可以從任何控制器方法中調用:

use function Illuminate\Support\defer;

Route::get('/user-profile', function () {
    defer(fn () => Analytics::report());

    return view('profile', ['user' => Auth::user()]);
});

延遲函數也可以使用 defer 方法添加到 Illuminate\Support\Carbon 實例:

Route::get('/user-profile', function () {
    Analytics::report();

    return view('profile', ['user' => Auth::user()]);
});

您可以使用 withoutVaporHeaders 方法從響應中排除延遲函數標頭:

Route::get('/user-profile', function () {
    defer(fn () => Analytics::report());

    return view('profile', ['user' => Auth::user()]);
})->withoutVaporHeaders();

Lottery

Laravel 的 Lottery 類別可用於對偶發行為執行基於機率的操作:

use Illuminate\Support\Lottery;

Lottery::odds(1, 100)->for(fn () => $logError());

Lottery::odds(20)->for(fn () => $reportMetrics());

Lottery::skip(10)->odds(1, 100)->for(fn () => $logError());

Lottery::times(10)->odds(1, 100)->for(fn () => $logError());

Lottery::dump()->odds(1, 100)->for(fn () => $logError());

您可以使用 assert 方法驗證是否調用了期望的機率回呼:

use Illuminate\Support\Facades\Lottery;

Lottery::fake();

Lottery::odds(1, 100)->for(fn () => $logError());

Lottery::assertNothingPassed();

Lottery::assertPassed(fn () => true, times: 1);

Lottery::assertNotPassed(fn () => true);

Pipeline

Laravel 的 Pipeline 類別允許您將一系列操作「管道化」到一個物件上。管道將物件透過處理器類別的管道進行傳遞,讓每個處理器都有機會檢查或修改物件並呼叫管道中的下一個處理器:

<?php

namespace App\Pipelines;

use Closure;

class EnsureUserHasSubscription
{
    /**
     * Handle an incoming request.
     */
    public function handle(object $request, Closure $next): mixed
    {
        if ($request->user()->hasActiveSubscription()) {
            return $next($request);
        }

        throw new SubscriptionRequiredException;
    }
}

處理器必須定義一個 handle 方法,該方法接受一個 $next 參數。調用 $next 方法會將 $request 繼續傳遞到管道中的下一個處理器:

<?php

namespace App\Http\Controllers;

use App\Pipelines\EnsureUserHasSubscription;
use Illuminate\Http\Request;
use Illuminate\Pipeline\Pipeline;

class UserController extends Controller
{
    /**
     * Update the user's profile.
     */
    public function update(Request $request): mixed
    {
        $response = app(Pipeline::class)
            ->send($request)
            ->through([
                EnsureUserHasSubscription::class,
            ])
            ->then(function (Request $request) {
                // ...
            });

        return $response;
    }
}

Sleep

Laravel 的 Sleep 類別在測試時為休眠和時間旅行提供了一個流暢的 API:

use Illuminate\Support\Carbon;
use Illuminate\Support\Sleep;

Sleep::fake();

Sleep::fake([Sleep::class => Sleep::for(5)->seconds()]);

// After 1 second...
Carbon::setTestNow(now()->addSeconds(1));

// After 3 seconds total...
Sleep::assertSleptTimes(3);

// In 5 minutes...
Carbon::setTestNow(now()->addMinutes(5));

Sleep::assertSlept(fn ($sleep) => $sleep->seconds() === 300);

Sleep::assertDidntSleep();

Timebox

Laravel 的 timebox 函數允許您將操作限制在預定義的時間限制內。當達到時間限制時,時間框將執行回呼中提供的任何剩餘操作:

use App\Models\User;
use Illuminate\Support\Timebox;

$user = (new Timebox)->timeBox(2000, function () {
    // 執行這個任務...
});

$user->first(); // [34.2ms]

URI

Laravel 的 Uri 類別提供了一個流暢的、可鏈接的介面,用於建立和操作 URI:

use Illuminate\Support\Uri;

$uri = Uri::build('https://laravel.com');
$uri = Uri::build('https://laravel.com')->withPath('/docs/13.x');
$uri = Uri::build('https://laravel.com')->withQuery(['page' => 1]);
$uri = Uri::build('https://laravel.com')->withFragment('section-5');

$uri = $uri->with([&39;framework' => 'laravel']);

$uri->getScheme(); // "https"
$uri->getHost(); // "laravel.com"
$uri->getPath(); // "/docs/13.x"
$uri->getQuery(); // "page=1&framework=laravel"
$uri->getFragment(); // "section-5"
$uri->getSchemeAndHttpHost(); // "https://laravel.com"
$uri->getFullUrl(); // "https://laravel.com/docs/13.x?page=1&framework=laravel#section-5"