> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 辅助函数

> 介绍 Laravel 提供的全局辅助函数以及 Arr、Number 类，并附上实用示例。

## 什么是辅助函数

Laravel 提供了大量全局 PHP 函数（辅助函数）。它们大多用于框架内部，但你也可以在应用中自由使用。

辅助函数大致分为以下几类：

* **数组 / 对象** — `Arr::` 类和 `data_get()` 等
* **数值** — `Number::` 类
* **路径** — `app_path()`、`storage_path()` 等
* **URL** — `route()`、`url()`、`asset()` 等
* **其他** — `config()`、`collect()`、`auth()` 等常用工具

<Info>
  全局辅助函数无需 `use` 声明即可任意调用。使用 `Arr` 或 `Number` 类时需要 `use Illuminate\Support\Arr;` 等 import。
</Info>

## 数组辅助（Arr 类）

### `Arr::get()` — 通过点号记法访问嵌套值

从多维数组中通过点号记法（`foo.bar.baz`）安全地取出嵌套值。键不存在时返回默认值。

```php theme={null}
use Illuminate\Support\Arr;

$config = [
    'database' => [
        'connections' => [
            'mysql' => ['host' => '127.0.0.1', 'port' => 3306],
        ],
    ],
];

$host = Arr::get($config, 'database.connections.mysql.host');
// '127.0.0.1'

$charset = Arr::get($config, 'database.connections.mysql.charset', 'utf8mb4');
```

<Tip>
  `data_get()` 全局函数功能相同，还支持 Eloquent 关系等 `Arrayable` 对象，适用面更广。
</Tip>

### `Arr::set()` — 向嵌套数组设置值

```php theme={null}
use Illuminate\Support\Arr;

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

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

### `Arr::has()` — 判断键是否存在

```php theme={null}
use Illuminate\Support\Arr;

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

$hasName = Arr::has($array, 'product.name'); // true

$hasAll = Arr::has($array, ['product.name', 'product.price']); // true
```

### `Arr::only()` / `Arr::except()` — 只保留 / 排除某些键

```php theme={null}
use Illuminate\Support\Arr;

$user = [
    'id' => 1,
    'name' => '山田太郎',
    'email' => 'yamada@example.com',
    'password' => 'secret',
    'role' => 'admin',
];

$safe = Arr::only($user, ['id', 'name', 'email']);

$public = Arr::except($user, ['password']);
```

### `Arr::pluck()` — 从嵌套数组抽取指定键

```php theme={null}
use Illuminate\Support\Arr;

$records = [
    ['user' => ['id' => 1, 'name' => '山田太郎']],
    ['user' => ['id' => 2, 'name' => '铃木花子']],
];

$names = Arr::pluck($records, 'user.name');

$nameById = Arr::pluck($records, 'user.name', 'user.id');
```

### `Arr::first()` / `Arr::last()` — 首个 / 末尾元素

```php theme={null}
use Illuminate\Support\Arr;

$prices = [150, 80, 200, 50, 120];

$first = Arr::first($prices, fn ($price) => $price >= 100);
// 150

$first = Arr::first($prices, fn ($price) => $price >= 500, 0);

$last = Arr::last($prices);
```

### `Arr::flatten()` — 多维数组扁平化为一维

```php theme={null}
use Illuminate\Support\Arr;

$tags = [
    'frontend' => ['html', 'css', 'javascript'],
    'backend'  => ['php', 'laravel', 'mysql'],
];

$allTags = Arr::flatten($tags);
```

### `Arr::wrap()` — 确保为数组

若值不是数组则用数组包裹。`null` 会变为空数组。方便让函数参数灵活接受多种输入。

```php theme={null}
use Illuminate\Support\Arr;

Arr::wrap('Laravel');     // ['Laravel']
Arr::wrap(['Laravel']);   // ['Laravel']
Arr::wrap(null);          // []
```

### `Arr::sort()` — 排序

```php theme={null}
use Illuminate\Support\Arr;

$fruits = ['banana', 'apple', 'cherry'];
$sorted = Arr::sort($fruits);

$products = [
    ['name' => '笔记本电脑', 'price' => 120000],
    ['name' => '鼠标', 'price' => 3500],
];

$byPrice = Arr::sort($products, fn ($product) => $product['price']);
```

### `Arr::dot()` / `Arr::undot()` — 点号记法互转

```php theme={null}
use Illuminate\Support\Arr;

$nested = [
    'user' => [
        'profile' => ['name' => '山田太郎', 'age' => 28],
    ],
];

$dotted = Arr::dot($nested);
// ['user.profile.name' => '山田太郎', 'user.profile.age' => 28]

$restored = Arr::undot($dotted);
```

### `Arr::join()` — 把数组连接为字符串

```php theme={null}
use Illuminate\Support\Arr;

$items = ['PHP', 'Laravel', 'MySQL'];

Arr::join($items, ', ');
// 'PHP, Laravel, MySQL'

Arr::join($items, ', ', ' 和 ');
// 'PHP, Laravel 和 MySQL'
```

## `data_get()` — 访问嵌套数据

`Arr::get()` 的通用版本，除数组外还支持对象、Eloquent 模型、集合。

```php theme={null}
$users = [
    ['name' => '山田太郎', 'address' => ['city' => '东京']],
    ['name' => '铃木花子', 'address' => ['city' => '大阪']],
];

$city = data_get($users, '0.address.city');

$cities = data_get($users, '*.address.city');
```

## 数值辅助（Number 类）

### `Number::format()`

```php theme={null}
use Illuminate\Support\Number;

Number::format(1234567.89);
// '1,234,567.89'
```

### `Number::currency()`

```php theme={null}
Number::currency(10000, 'JPY', locale: 'ja');
// '￥10,000'

Number::currency(29.99, 'USD');
// '$29.99'
```

### `Number::fileSize()`

```php theme={null}
Number::fileSize(1024);         // '1 KB'
Number::fileSize(1024 * 1024 * 2.5); // '2.5 MB'
```

### `Number::abbreviate()`

```php theme={null}
Number::abbreviate(1000);     // '1K'
Number::abbreviate(1500000);  // '1.5M'
```

### `Number::percentage()`

```php theme={null}
Number::percentage(75.5, precision: 1); // '75.5%'
```

## 路径辅助

获取应用内目录路径。即使部署环境改变也能返回正确路径。

```php theme={null}
app_path();                                     // app 目录
app_path('Http/Controllers/UserController.php');
base_path('composer.json');
config_path('database.php');
database_path('migrations');
storage_path('app/uploads');
public_path('css/app.css');
resource_path('views/welcome.blade.php');
```

## URL 辅助

### `route()`

```php theme={null}
// 绝对 URL（默认）
$url = route('users.show', ['user' => 1]);

// 相对 URL
$url = route('users.show', ['user' => 1], false);
```

### `url()`

```php theme={null}
$url = url('user/profile');

$current  = url()->current();
$full     = url()->full();
$previous = url()->previous();
```

### `asset()`

```php theme={null}
$url = asset('img/logo.png');
```

### `to_route()`

```php theme={null}
return to_route('users.show', ['user' => 1]);

return to_route('users.show', ['user' => 1], 302, ['X-Custom' => 'value']);
```

## 其他常用辅助

### `config()`

```php theme={null}
$timezone = config('app.timezone');
$debug = config('app.debug', false);
config(['app.locale' => 'ja']);
```

### `collect()`

```php theme={null}
$collection = collect([1, 2, 3, 4, 5]);
$sum = collect([1, 2, 3])->sum();
```

<Tip>
  `collect()` 是进入集合的关键辅助。详见[集合](/zh/collections)。
</Tip>

### `auth()`

```php theme={null}
$user = auth()->user();

if (auth()->check()) {
    // 已登录
}

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

### `blank()` / `filled()`

`blank()` 将 `null`、空字符串、纯空格、空集合、空数组视为 `true`。`filled()` 相反。

```php theme={null}
blank('');         // true
blank('   ');      // true
blank(null);       // true
blank(collect()); // true

blank(0);      // false
blank(false);  // false

filled('hello'); // true
filled(0);       // true
```

### `abort()` / `abort_if()` / `abort_unless()`

```php theme={null}
abort(404);
abort(403, '无权访问此页面。');

abort_if(! auth()->user()->isAdmin(), 403);
abort_unless(auth()->check(), 401);
```

### `dd()` / `dump()`

```php theme={null}
dd($user);          // 输出后终止
dd($user, $orders, $config);

dump($query);       // 输出后继续
```

### `dispatch()`

```php theme={null}
dispatch(new App\Jobs\SendWelcomeEmail($user));
dispatch_sync(new App\Jobs\GenerateReport($data));
```

### `encrypt()` / `decrypt()`

```php theme={null}
$encrypted = encrypt('sensitive-value');
$decrypted = decrypt($encrypted);
```

### `env()`

```php theme={null}
$debug = env('APP_DEBUG', false);
$dbHost = env('DB_HOST', '127.0.0.1');
```

<Warning>
  最佳实践是在 `config/` 中调用 `env()`，而不是在控制器 / 服务类中直接使用；通过 `config()` 访问值。执行 `php artisan config:cache` 后，`env()` 可能不会返回预期值。
</Warning>

## `Arr` 与 `collect()` 的选择

`Arr::` 类作用于普通 PHP 数组，`collect()` 返回集合对象。

```php theme={null}
use Illuminate\Support\Arr;

// 想保持数组形式 → Arr
$filtered = Arr::where($items, fn ($v) => $v > 0);

// 需要链式操作 → collect()
$result = collect($items)
    ->filter(fn ($v) => $v > 0)
    ->map(fn ($v) => $v * 2)
    ->values()
    ->all();
```

<Info>
  Eloquent 的结果本身就是集合，无需再用 `collect()` 包裹。若只是简单数组操作，`Arr::` 更简洁。
</Info>

## 小结

<AccordionGroup>
  <Accordion title="常用辅助函数列表">
    | 辅助函数                                  | 用途         |
    | ------------------------------------- | ---------- |
    | `Arr::get($array, 'a.b.c', $default)` | 从嵌套数组中安全取值 |
    | `Arr::only($array, $keys)`            | 只保留指定键     |
    | `Arr::except($array, $keys)`          | 排除指定键      |
    | `Arr::pluck($array, 'key')`           | 抽取键值列表     |
    | `Arr::flatten($array)`                | 多维数组扁平化    |
    | `Arr::wrap($value)`                   | 确保为数组      |
    | `data_get($target, 'a.*.b')`          | 通配符访问      |
    | `Number::format($n)`                  | 格式化数值      |
    | `Number::currency($n, 'JPY')`         | 货币展示       |
    | `Number::fileSize($bytes)`            | 文件大小展示     |
    | `route('name', $params)`              | 命名路由 URL   |
    | `url('path')`                         | 绝对 URL     |
    | `asset('path')`                       | 资源 URL     |
    | `config('key', $default)`             | 读取配置       |
    | `collect($array)`                     | 创建集合       |
    | `auth()->user()`                      | 当前用户       |
    | `blank($value)`                       | 判空         |
    | `filled($value)`                      | 非空         |
    | `abort(403)`                          | 抛出 HTTP 异常 |
    | `dispatch($job)`                      | 派发任务       |
    | `env('KEY', $default)`                | 读取环境变量     |
  </Accordion>

  <Accordion title="Arr 类 vs collect()">
    **适合 `Arr::` 的场景**：

    * 简单数组操作（嵌套键访问、键筛选等）
    * 不需要集合对象的开销
    * 想保持数组形式的结果

    **适合 `collect()` 的场景**：

    * 需要多个操作链式表达
    * 加工 Eloquent 结果（已是集合）
    * 想用 `map`、`filter`、`groupBy` 等集合专属方法
  </Accordion>
</AccordionGroup>


## Related topics

- [本地化](/zh/localization.md)
- [tap() 辅助函数与 Tappable trait](/zh/advanced/tap.md)
- [门面](/zh/facades.md)
- [错误处理](/zh/error-handling.md)
- [Fluent 类](/zh/advanced/fluent.md)
