Laravel 13 辅助函数完全手册

Laravel 提供了丰富的辅助函数,帮助开发者快速完成常见任务。本文将全面介绍 Laravel 13 中可用的辅助函数及其最佳实践。

数组函数

数组访问

1
2
3
4
5
6
7
8
9
10
$array = ['products' => ['desk' => ['price' => 100]]];

$value = array_get($array, 'products.desk.price'); // 100
$value = array_get($array, 'products.desk.discount', 0); // 0 (默认值)

array_set($array, 'products.desk.price', 200);
array_set($array, 'products.desk.color', 'black');

array_has($array, 'products.desk'); // true
array_has($array, 'products.chair'); // false

数组操作

1
2
3
4
5
6
7
8
9
10
$array = ['name' => 'Desk', 'price' => 100];

array_only($array, ['name']); // ['name' => 'Desk']
array_except($array, ['price']); // ['name' => 'Desk']

$array = [100, 200, 300];
array_first($array, fn($value) => $value >= 150); // 200
array_last($array, fn($value) => $value >= 150); // 300

array_pluck([['name' => 'Desk'], ['name' => 'Chair']], 'name'); // ['Desk', 'Chair']

数组转换

1
2
3
4
5
6
7
$array = ['name' => 'Desk', 'price' => 100];

array_keys_to_camel(['first_name' => 'John']); // ['firstName' => 'John']
array_keys_to_snake(['firstName' => 'John']); // ['first_name' => 'John']

array_collapse([[1, 2], [3, 4]]); // [1, 2, 3, 4]
array_flatten(['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]); // ['Joe', 'PHP', 'Ruby']

数组分组与排序

1
2
3
4
5
6
7
8
9
10
11
$users = [
['name' => 'John', 'role' => 'admin'],
['name' => 'Jane', 'role' => 'user'],
['name' => 'Bob', 'role' => 'admin'],
];

array_group_by($users, 'role');
// ['admin' => [...], 'user' => [...]]

array_sort_by($users, 'name');
array_sort_by_desc($users, 'name');

字符串函数

基础字符串操作

1
2
3
4
5
6
7
8
9
str_after('This is a test', 'This is'); // ' a test'
str_before('This is a test', 'test'); // 'This is a '
str_between('This is a test', 'This', 'test'); // ' is a '

str_contains('This is a test', 'is'); // true
str_contains('This is a test', ['is', 'test']); // true

str_starts_with('This is a test', 'This'); // true
str_ends_with('This is a test', 'test'); // true

字符串转换

1
2
3
4
5
6
7
8
9
10
11
str_camel('foo_bar'); // 'fooBar'
str_snake('fooBar'); // 'foo_bar'
str_kebab('fooBar'); // 'foo-bar'
str_studly('foo_bar'); // 'FooBar'
str_title('foo bar'); // 'Foo Bar'
str_slug('Laravel 13 Framework', '-'); // 'laravel-13-framework'

str_lower('HELLO'); // 'hello'
str_upper('hello'); // 'HELLO'
str_ucfirst('hello world'); // 'Hello world'
str_ucsplit('HelloWorld'); // ['Hello', 'World']

字符串处理

1
2
3
4
5
6
7
8
9
10
11
str_limit('The quick brown fox jumps over the lazy dog', 20); // 'The quick brown fox...'
str_words('The quick brown fox', 3); // 'The quick brown...'
str_word_count('The quick brown fox'); // 4

str_replace_first('the', 'a', 'the quick the fox'); // 'a quick the fox'
str_replace_last('the', 'a', 'the quick the fox'); // 'the quick a fox'

str_random(16); // 随机16字符字符串
str_random_bytes(32); // 随机32字节
str_uuid(); // UUID
str_ulid(); // ULID

字符串匹配

1
2
3
4
5
6
7
str_is('foo*', 'foobar'); // true
str_is('ba*', 'foobar'); // false

str_match('/\d+/', 'User 123'); // '123'
str_match_all('/\d+/', 'User 123, ID 456'); // ['123', '456']

str_replace_array('?', ['1', '2', '3'], '?/?/?'); // '1/2/3'

Stringable 链式操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
use Illuminate\Support\Str;

$string = Str::of(' Laravel Framework ')
->trim()
->lower()
->replace(' ', '-')
->slug()
->limit(15);

// 'laravel-framew...'

Str::of('Laravel Framework')
->words(2, '...')
->title();
// 'Laravel Framework...'

Str::of('{"name":"John"}')
->jsonDecode()
->get('name');
// 'John'

路径函数

1
2
3
4
5
6
7
8
9
10
11
base_path(); // 应用根目录
app_path(); // app 目录
config_path(); // config 目录
database_path(); // database 目录
lang_path(); // lang 目录
public_path(); // public 目录
resource_path(); // resource 目录
storage_path(); // storage 目录

base_path('vendor/bin'); // '/path/to/project/vendor/bin'
app_path('Http/Controllers'); // '/path/to/project/app/Http/Controllers'

URL 函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
url('/users'); // 'https://example.com/users'
url('/users', ['sort' => 'name']); // 'https://example.com/users?sort=name'
url()->current(); // 当前 URL
url()->full(); // 包含查询字符串的完整 URL
url()->previous(); // 上一个 URL

route('users.show', ['user' => 1]); // 路由 URL
route('users.index', ['page' => 2], false); // 相对 URL

action([UserController::class, 'index']); // 控制器动作 URL
action([UserController::class, 'show'], ['user' => 1]);

asset('images/logo.png'); // 资源 URL
secure_asset('images/logo.png'); // HTTPS 资源 URL

安全函数

1
2
3
4
5
6
7
8
9
10
11
bcrypt('secret'); // Bcrypt 哈希
hash('sha256', 'data'); // SHA-256 哈希

csrf_token(); // CSRF 令牌
csrf_field(); // CSRF 隐藏字段 HTML

encrypt('secret'); // 加密
decrypt($encrypted); // 解密

old('email'); // 旧输入值
old('email', 'default@example.com'); // 带默认值

认证函数

1
2
3
4
5
6
7
8
9
auth(); // 认证管理器
auth()->user(); // 当前用户
auth()->id(); // 当前用户 ID
auth()->check(); // 是否已登录
auth()->guest(); // 是否访客

auth('admin')->user(); // 使用 admin guard
auth()->login($user); // 登录用户
auth()->logout(); // 登出

缓存函数

1
2
3
4
5
6
cache('key'); // 获取缓存
cache('key', 'default'); // 带默认值
cache(['key' => 'value'], 3600); // 设置缓存
cache()->remember('users', 3600, fn() => User::all());
cache()->forget('key');
cache()->flush();
1
2
3
4
cookie('name', 'value', 60); // 创建 Cookie
cookie('name', 'value', 60, '/', null, true, true); // HttpOnly, Secure

request()->cookie('name'); // 获取 Cookie

数据库函数

1
2
3
4
5
6
7
8
9
10
11
db(); // 数据库管理器
db()->table('users')->get();
db()->connection('mysql')->table('users')->get();

db()->transaction(function () {
// 事务操作
});

db()->beginTransaction();
db()->commit();
db()->rollBack();

事件函数

1
2
3
event(new UserRegistered($user)); // 触发事件

event('user.registered', [$user]); // 触发类事件

日志函数

1
2
3
4
info('User logged in', ['id' => 1]);
logger('Debug message');
logger()->error('Error occurred', ['exception' => $e]);
logger()->channel('slack')->info('Alert!');

邮件函数

1
2
mail(new OrderShipped($order));
mail($user, new WelcomeEmail());

模型函数

1
2
3
4
5
6
7
8
9
10
11
12
user(); // 当前认证用户
user('admin'); // admin guard 用户

optional($user)->name; // 安全访问
optional(null)->name; // null

throw_if($condition, new Exception('Error'));
throw_unless($condition, new Exception('Error'));

retry(3, function () {
return Http::get('https://example.com');
}, 100); // 重试3次,间隔100ms

响应函数

1
2
3
4
5
6
7
8
9
10
11
12
response('Hello', 200);
response()->json(['name' => 'John']);
response()->download($file);
response()->stream($callback, 200, $headers);

redirect('/home');
redirect()->route('home');
redirect()->back();
redirect()->action([HomeController::class, 'index']);

view('welcome');
view('users.index', ['users' => $users]);

集合函数

1
2
3
4
5
collect([1, 2, 3]); // 创建集合
collect(['name' => 'John', 'age' => 30]); // 关联数组集合

collect([1, 2, 3])->map(fn($n) => $n * 2); // [2, 4, 6]
collect([1, 2, 3])->filter(fn($n) => $n > 1); // [2, 3]

视图函数

1
2
3
4
view('welcome');
view('layouts.app');
view()->exists('emails.welcome'); // 检查视图是否存在
view()->share('key', 'value'); // 共享数据

其他实用函数

环境与配置

1
2
3
4
5
6
7
8
9
10
11
12
app(); // 应用实例
app('config'); // 配置仓库
app()->environment(); // 当前环境
app()->environment('local'); // 是否本地环境
app()->environment(['local', 'testing']); // 多环境检测

config('app.timezone');
config('app.name', 'Laravel'); // 带默认值
config(['app.debug' => true]); // 运行时设置

env('APP_DEBUG', false);
env('DB_HOST', 'localhost');

调试函数

1
2
3
4
5
6
7
dd($value); // 打印并停止
dump($value); // 打印继续执行

ray($value); // 使用 Ray 调试

report($exception); // 报告异常
report_if($condition, $exception);

请求函数

1
2
3
4
5
6
7
8
9
10
11
12
request(); // 当前请求
request('name'); // 获取输入
request('name', 'default'); // 带默认值
request()->all(); // 所有输入
request()->only(['name', 'email']);
request()->except(['password']);
request()->file('avatar');
request()->has('name');
request()->filled('name');
request()->method(); // HTTP 方法
request()->isMethod('post');
request()->wantsJson();

会话函数

1
2
3
4
5
6
session('key'); // 获取会话值
session('key', 'default'); // 带默认值
session(['key' => 'value']); // 设置会话
session()->flash('status', 'Task completed!');
session()->reflash(); // 刷新闪存
session()->forget('key'); // 删除

翻译函数

1
2
3
4
5
__('Welcome'); // 翻译
__('messages.welcome'); // 命名翻译
__('messages.welcome', ['name' => 'John']); // 带参数
trans('messages.welcome');
trans_choice('messages.apples', 10); // 复数形式

验证函数

1
2
3
4
validator($data, $rules);
validator($data, $rules)->validate();

validated($data, $rules); // 验证并返回验证数据

创建自定义辅助函数

定义辅助函数文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

if (!function_exists('format_currency')) {
function format_currency($amount, $currency = 'USD'): string
{
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
return $formatter->formatCurrency($amount, $currency);
}
}

if (!function_exists('user_can')) {
function user_can($ability, $arguments = []): bool
{
return auth()->user()?->can($ability, $arguments) ?? false;
}
}

自动加载配置

1
2
3
4
5
6
7
{
"autoload": {
"files": [
"app/helpers.php"
]
}
}

总结

Laravel 13 的辅助函数提供了:

  • 快速便捷的数组操作
  • 强大的字符串处理能力
  • 简洁的路由和 URL 生成
  • 完善的安全和认证支持
  • 灵活的响应和视图处理
  • 可扩展的自定义函数

熟练掌握这些辅助函数,可以大大提高开发效率,编写更简洁优雅的代码。