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

# Helper functions

> Learn about Laravel's global helper functions and the Arr and Number classes with practical examples.

## What are helper functions

Laravel provides a large number of global PHP functions (helpers). While the framework itself uses most of them internally, you're free to use them in your application as well.

Helpers fall into these main categories:

* **Arrays and objects** — the `Arr::` class and functions like `data_get()`
* **Numbers** — the `Number::` class
* **Paths** — path retrieval functions like `app_path()` and `storage_path()`
* **URLs** — URL generation functions like `route()`, `url()`, and `asset()`
* **Miscellaneous** — commonly used utilities like `config()`, `collect()`, and `auth()`

<Info>
  Helper functions can be called from anywhere without a `use` declaration. To use the `Arr` or `Number` class, you need imports like `use Illuminate\Support\Arr;`.
</Info>

## Array helpers (Arr class)

### `Arr::get()` — retrieve nested values using dot notation

Safely retrieve nested values from a multi-dimensional array using dot notation (`foo.bar.baz`). Returns a default value if the key does not exist.

```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'

// Default value if the key does not exist
$charset = Arr::get($config, 'database.connections.mysql.charset', 'utf8mb4');
// 'utf8mb4'
```

<Tip>
  The `data_get()` global function has the same capability. It also handles `Arrayable` objects (such as Eloquent relationships), so it's usable in more general situations.
</Tip>

### `Arr::set()` — set a value in a nested array

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

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

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

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

### `Arr::has()` — check if a key exists

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

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

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

// Verify that all of multiple keys are present
$hasAll = Arr::has($array, ['product.name', 'product.price']);
// true
```

### `Arr::only()` / `Arr::except()` — filter or exclude keys

Handy when you want to extract only the necessary keys from request data or configuration arrays, or exclude unneeded keys.

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

$user = [
    'id' => 1,
    'name' => 'Taro Yamada',
    'email' => 'yamada@example.com',
    'password' => 'secret',
    'role' => 'admin',
];

// Take only the necessary keys
$safe = Arr::only($user, ['id', 'name', 'email']);
// ['id' => 1, 'name' => 'Taro Yamada', 'email' => 'yamada@example.com']

// Exclude only password
$public = Arr::except($user, ['password']);
// ['id' => 1, 'name' => 'Taro Yamada', 'email' => '...', 'role' => 'admin']
```

### `Arr::pluck()` — extract a specific key from a nested array

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

$records = [
    ['user' => ['id' => 1, 'name' => 'Taro Yamada']],
    ['user' => ['id' => 2, 'name' => 'Hanako Suzuki']],
];

$names = Arr::pluck($records, 'user.name');
// ['Taro Yamada', 'Hanako Suzuki']

// Specify a key via the third argument
$nameById = Arr::pluck($records, 'user.name', 'user.id');
// [1 => 'Taro Yamada', 2 => 'Hanako Suzuki']
```

### `Arr::first()` / `Arr::last()` — the first/last element that matches a condition

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

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

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

// Default value when the condition is not satisfied
$first = Arr::first($prices, fn ($price) => $price >= 500, 0);
// 0

// The last element (no condition)
$last = Arr::last($prices);
// 120
```

### `Arr::flatten()` — flatten a multi-dimensional array

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

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

$allTags = Arr::flatten($tags);
// ['html', 'css', 'javascript', 'php', 'laravel', 'mysql']
```

### `Arr::wrap()` — ensure a value is an array

If the value is not an array, wrap it in one. `null` becomes an empty array. Useful when accepting flexible arguments to functions.

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

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

Arr::wrap(['Laravel', 'PHP']);
// ['Laravel', 'PHP']

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

### `Arr::sort()` — sort by value

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

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

// Specify a sort key via a closure
$products = [
    ['name' => 'Laptop', 'price' => 120000],
    ['name' => 'Mouse', 'price' => 3500],
    ['name' => 'Keyboard', 'price' => 8000],
];

$byPrice = Arr::sort($products, fn ($product) => $product['price']);
// Order: Mouse, Keyboard, Laptop
```

### `Arr::dot()` / `Arr::undot()` — convert to and from dot notation

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

$nested = [
    'user' => [
        'profile' => ['name' => 'Taro Yamada', 'age' => 28],
    ],
];

$dotted = Arr::dot($nested);
// ['user.profile.name' => 'Taro Yamada', 'user.profile.age' => 28]

// Restore the original structure
$restored = Arr::undot($dotted);
// ['user' => ['profile' => ['name' => 'Taro Yamada', 'age' => 28]]]
```

### `Arr::join()` — join an array into a string

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

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

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

// Use a different separator before the last element
Arr::join($items, ', ', ' and ');
// 'PHP, Laravel and MySQL'
```

## `data_get()` — access nested data

The general-purpose version of `Arr::get()`. It supports not just arrays but also objects, Eloquent models, and collections.

```php theme={null}
$users = [
    ['name' => 'Taro Yamada', 'address' => ['city' => 'Tokyo']],
    ['name' => 'Hanako Suzuki', 'address' => ['city' => 'Osaka']],
];

// Access with dot notation
$city = data_get($users, '0.address.city');
// 'Tokyo'

// Get from all elements with wildcards
$cities = data_get($users, '*.address.city');
// ['Tokyo', 'Osaka']
```

## Number helpers (Number class)

### `Number::format()` — format numbers for readability

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

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

Number::format(1234567.89, precision: 0, locale: 'ja');
// '1,234,568'
```

### `Number::currency()` — currency formatting

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

Number::currency(10000, 'JPY', locale: 'ja');
// '￥10,000'

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

### `Number::fileSize()` — human-readable file sizes

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

Number::fileSize(1024);
// '1 KB'

Number::fileSize(1024 * 1024 * 2.5);
// '2.5 MB'
```

### `Number::abbreviate()` — abbreviate large numbers

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

Number::abbreviate(1000);
// '1K'

Number::abbreviate(1500000);
// '1.5M'
```

### `Number::percentage()` — display as a percentage

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

Number::percentage(75.5, precision: 1);
// '75.5%'
```

## Path helpers

Retrieve directory paths within your application. They return the correct path regardless of environment or deployment target.

```php theme={null}
// Absolute path to the app directory
app_path();
// /var/www/html/app

// Path to app/Http/Controllers/UserController.php
app_path('Http/Controllers/UserController.php');

// Relative to the project root
base_path('composer.json');

// The config directory
config_path('database.php');

// The database directory
database_path('migrations');

// The storage directory
storage_path('app/uploads');

// The public directory
public_path('css/app.css');

// The resources directory
resource_path('views/welcome.blade.php');
```

## URL helpers

### `route()` — generate a URL for a named route

```php theme={null}
// Route definition
// Route::get('/users/{user}', [UserController::class, 'show'])->name('users.show');

// Absolute URL (default)
$url = route('users.show', ['user' => 1]);
// 'https://example.com/users/1'

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

### `url()` — absolute URL for an arbitrary path

```php theme={null}
$url = url('user/profile');
// 'https://example.com/user/profile'

// Get a URL generator instance
$current  = url()->current();   // Current URL
$full     = url()->full();      // Current URL including query string
$previous = url()->previous();  // Previous URL
```

### `asset()` — URL for a static asset

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

### `to_route()` — redirect to a named route

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

// You can also specify HTTP status and headers
return to_route('users.show', ['user' => 1], 302, ['X-Custom' => 'value']);
```

## Other commonly used helpers

### `config()` — get and set configuration values

```php theme={null}
// Get a configuration value with dot notation
$timezone = config('app.timezone');
// 'Asia/Tokyo'

// With a default value
$debug = config('app.debug', false);

// Change configuration at runtime (limited to that process)
config(['app.locale' => 'ja']);
```

### `collect()` — create a collection

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

$sum = collect([1, 2, 3])->sum(); // 6
```

<Tip>
  `collect()` is the most important helper as the entry point to collections. See [Collections](/en/collections) for details.
</Tip>

### `auth()` — get the authenticated user

```php theme={null}
// Get the current user
$user = auth()->user();

// Check whether they're logged in
if (auth()->check()) {
    // Logic for authenticated users
}

// Use a specific guard
$admin = auth('admin')->user();
```

### `blank()` / `filled()` — check for emptiness

`blank()` treats `null`, empty string, whitespace-only, empty collections, and empty arrays as `true`. `filled()` is the inverse.

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

blank(0);      // false (0 is not "blank")
blank(false);  // false

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

### `abort()` / `abort_if()` / `abort_unless()` — HTTP exceptions

```php theme={null}
// Throw an HTTP error directly
abort(404);
abort(403, 'You do not have permission to access this page.');

// Error when the condition is true
abort_if(! auth()->user()->isAdmin(), 403);

// Error when the condition is false
abort_unless(auth()->check(), 401);
```

### `dd()` / `dump()` — debugging

```php theme={null}
// Print variables and terminate the script
dd($user);
dd($user, $orders, $config);

// Print without terminating the script
dump($query);
```

### `dispatch()` — push a job onto the queue

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

// Run immediately (synchronously)
dispatch_sync(new App\Jobs\GenerateReport($data));
```

### `encrypt()` / `decrypt()` — encryption

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

### `env()` — get an environment variable

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

<Warning>
  Best practice is to not call `env()` directly from controllers or service classes, but rather to call it inside `config/` files and access the values via `config()`. When configuration caching (`php artisan config:cache`) is enabled, `env()` may not return the value you expect.
</Warning>

## Choosing between the Arr class and collect()

The `Arr::` class operates on regular PHP arrays; `collect()` returns collection objects.

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

// When you want to keep working with arrays → Arr class
$filtered = Arr::where($items, fn ($v) => $v > 0);
// The result is an array

// When you want to chain multiple operations → collect()
$result = collect($items)
    ->filter(fn ($v) => $v > 0)
    ->map(fn ($v) => $v * 2)
    ->values()
    ->all();
// The result is an array (extracted with all())
```

<Info>
  Eloquent results are automatically returned as collections, so there's no need to wrap them with `collect()`. When simple array operations are enough, using `Arr::` keeps things simpler.
</Info>

## Summary

<AccordionGroup>
  <Accordion title="Common helpers reference">
    | Helper                                | Purpose                            |
    | ------------------------------------- | ---------------------------------- |
    | `Arr::get($array, 'a.b.c', $default)` | Safely fetch from a nested array   |
    | `Arr::only($array, $keys)`            | Keep only the specified keys       |
    | `Arr::except($array, $keys)`          | Exclude the specified keys         |
    | `Arr::pluck($array, 'key')`           | Fetch the values of a specific key |
    | `Arr::flatten($array)`                | Flatten a multi-dimensional array  |
    | `Arr::wrap($value)`                   | Ensure the value is an array       |
    | `data_get($target, 'a.*.b')`          | Fetch with wildcards               |
    | `Number::format($n)`                  | Format a number for readability    |
    | `Number::currency($n, 'JPY')`         | Currency display                   |
    | `Number::fileSize($bytes)`            | Human-readable file size           |
    | `route('name', $params)`              | URL to a named route               |
    | `url('path')`                         | Generate an absolute URL           |
    | `asset('path')`                       | URL to a static asset              |
    | `config('key', $default)`             | Retrieve a configuration value     |
    | `collect($array)`                     | Create a collection                |
    | `auth()->user()`                      | Get the current user               |
    | `blank($value)`                       | Check for emptiness                |
    | `filled($value)`                      | Check for non-emptiness            |
    | `abort(403)`                          | Throw an HTTP exception            |
    | `dispatch($job)`                      | Push a job onto the queue          |
    | `env('KEY', $default)`                | Get an environment variable        |
  </Accordion>

  <Accordion title="Arr class vs collect()">
    **When to use the `Arr::` class**:

    * Simple array operations (accessing nested keys, filtering keys, etc.)
    * When the collection object's overhead is unnecessary
    * When you want to keep the result as an array

    **When to use `collect()`**:

    * When you want to express multiple operations via method chains
    * When further transforming Eloquent results (already collections)
    * When you want to use collection-specific methods like `map`, `filter`, or `groupBy`
  </Accordion>
</AccordionGroup>


## Related topics

- [Facades](/en/facades.md)
- [Fluent Class](/en/advanced/fluent.md)
- [Session](/en/session.md)
- [Processes](/en/processes.md)
- [Build SPAs with Inertia.js](/en/blog/inertia-introduction.md)
