Laravel 提供了大量实用的全局辅助函数(Helpers)和强大的集合(Collection)类,它们能极大地简化数组、对象、字符串的操作,让代码更加简洁易读。本章将系统讲解常用辅助函数和集合的高阶用法,助你写出更优雅的 Laravel 代码。
// 获取数组元素,支持默认值
$value = data_get($array, 'user.name', 'default');
$value = data_get($object, 'user.name');
// 设置数组元素
data_set($array, 'user.name', 'John');
// 数组/对象填充默认值(仅当键不存在)
$result = data_fill($array, 'user.age', 25);
// 从数组中取指定键
$filtered = array_only($array, ['name', 'email']);
// 排除指定键
$filtered = array_except($array, ['password']);
// 字符串截取
$str = Str::limit('The quick brown fox jumps over the lazy dog', 20);
// "The quick brown fox..."
// 判断字符串包含
$contains = str_contains('Hello World', 'World'); // true
// 判断以某字符串开头/结尾
str_starts_with('Hello World', 'Hello'); // true
str_ends_with('Hello World', 'World'); // true
// 生成随机字符串
$random = Str::random(32);
// 生成 UUID
$uuid = Str::uuid();
// 字符串转驼峰/蛇形
$camel = Str::camel('hello_world'); // helloWorld
$snake = Str::snake('helloWorld'); // hello_world
// 获取各种路径
$app_path = app_path(); // app 目录
$base_path = base_path(); // 项目根目录
$config_path = config_path(); // config 目录
$public_path = public_path(); // public 目录
$storage_path = storage_path(); // storage 目录
$resource_path = resource_path(); // resources 目录
// 拼接路径
$path = public_path('css/app.css');
// 打印变量并停止执行
dd($variable);
// 打印变量但不停止
dump($variable);
// 打印并记录日志
logger('Something happened', ['user' => $user]);
// 记录信息到日志
info('User logged in', ['id' => $user->id]);
error('Failed to process order', ['order' => $order]);
// 获取环境变量值
$env = env('APP_ENV', 'production');
// 获取配置值
$timezone = config('app.timezone');
// 生成 URL
$url = url('/user/profile');
$route = route('user.profile', ['id' => 1]);
// 生成视图
return view('welcome', ['name' => 'John']);
// 响应 JSON
return response()->json(['status' => 'success']);
// 执行 Artisan 命令
$exitCode = Artisan::call('cache:clear');
// 重定向
return redirect()->route('home');
集合是 Laravel 对数组的封装,提供了流畅、方便的链式操作。几乎所有 Eloquent 查询返回的结果都是集合,你也可以手动创建集合。
use Illuminate\Support\Collection;
// 从数组创建
$collection = collect([1, 2, 3]);
// 从 range 创建
$collection = collect(range(1, 10));
// 空集合
$collection = collect();
| 方法 | 说明 |
|---|---|
map(callable) | 对每个元素应用回调,返回新集合 |
filter(callable) | 过滤集合,保留回调返回 true 的元素 |
reject(callable) | 与 filter 相反,移除符合条件的元素 |
reduce(callable, $initial) | 迭代归约,返回累加值 |
each(callable) | 遍历集合,不改变原集合 |
pluck($key) | 提取指定键的值 |
sum($key = null) | 求和 |
avg($key = null) | 平均值 |
sortBy($key) | 按指定键排序 |
groupBy($key) | 按指定键分组 |
chunk($size) | 将集合分成多个指定大小的块 |
first() | 返回第一个元素 |
last() | 返回最后一个元素 |
count() | 返回元素个数 |
isEmpty() | 是否为空 |
$users = collect([
['name' => 'John', 'age' => 25, 'active' => true],
['name' => 'Jane', 'age' => 30, 'active' => false],
['name' => 'Bob', 'age' => 28, 'active' => true],
]);
// 获取所有激活用户的名字并转为大写
$activeNames = $users
->filter(fn($user) => $user['active'])
->map(fn($user) => strtoupper($user['name']))
->values(); // 重置索引
// ['JOHN', 'BOB']
集合支持调用对象方法的高阶消息传递,使代码更简洁:
// 传统写法
$names = $users->map(function ($user) {
return $user->name;
});
// 高阶消息传递(PHP 7.4+)
$names = $users->map->name;
// 再结合 filter
$activeNames = $users->filter->active->map->name;
// 将集合打乱顺序
$shuffled = $collection->shuffle();
// 取前 N 个
$firstThree = $collection->take(3);
// 去重
$unique = $collection->unique();
// 合并两个集合
$merged = $collection1->merge($collection2);
// 交叉连接
$cross = $collection1->crossJoin($collection2);
// 随机取出一个元素
$random = $collection->random();
// 将集合转换为数组
$array = $collection->toArray();
// 转换为 JSON
$json = $collection->toJson();
你可以通过 macro 方法为集合添加自定义方法,方便复用。通常在服务提供者中注册:
use Illuminate\Support\Collection;
Collection::macro('toUpper', function () {
return $this->map(function ($value) {
return strtoupper($value);
});
});
// 使用
$collection = collect(['a', 'b', 'c']);
$upper = $collection->toUpper(); // ['A', 'B', 'C']
LazyCollection 可以降低内存占用。collect())更简洁,Facade 有时更明确(如 Str::limit()),根据场景选择。dd(): 调试时使用,但提交代码前应移除或改用日志。LazyCollection,它支持分批处理,显著降低内存消耗。详细内容可查阅官方文档。
Laravel 的辅助函数和集合是日常开发的得力工具。掌握它们不仅能提高编码效率,还能让代码更加清晰、易维护。建议你在项目中多实践集合的链式操作,并熟悉常用辅助函数,它们会帮助你以更少的代码完成更多工作。