在本文章中,我们将更深入地探讨我们都使用的 Laravel 的各个部分,以揭示我们可以在下一个项目中使用的功能和特性......如果我们了解它们就好了!
以下是一些鲜为人知的收集方法,在各种实际场景中非常有用:
- macro():这允许您向 Laravel 集合添加可在任何集合实例上使用的自定义方法:
use Illuminate\Support\Collection;
Collection::macro('customMethod', function () {
// Your custom method logic
});
$collection = collect([...]);
// use on any collection object
$result = $collection->customMethod();
- concat():假设您有两个来自不同来源的用户集合,并希望将它们合并为一个集合。您可以
concat
为此目的使用:
$usersFromDatabase = User::where(...)->get();
$usersFromApi = collect([...]);
$combinedUsers = $usersFromDatabase->concat($usersFromApi);
- pad():您有一个任务集合,但您想确保它始终包含最少数量的元素。
pad
如有必要,您可以使用它来添加虚拟任务:
$tasks = collect([...]);
$paddedTasks = $tasks->pad(10, 'Dummy Task');
- shuffle() & random():假设您有一个测验应用程序,并且想要打乱问题的顺序。您可以使用
shuffle
它来实现此目的。此外,如果您要从集合中随机选择一个问题,您可以使用random
:
$questions = collect([...]);
$shuffledQuestions = $questions->shuffle();
$randomQuestion = $questions->random();
- crossJoin():假设您有两个集合,并且想要从它们中生成所有可能的组合。
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b']);
$matrix->all();
/*[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]*/
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);
$matrix->all();
/*[
[1, 'a', 'I'],
[1, 'a', 'II'],
[1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
] */
- partion():假设您有一群学生,您想根据他们的成绩(通过或不通过)将他们分成两组。
partition
这很容易:
$students = collect([...]);
list($passingStudents, $failingStudents) = $students->partition(function ($student) {
return $student->grade >= 60;
});
- first()和firstWhere():您有一个任务集合,并且想要检索第一个任务或满足特定条件的第一个任务。
first
并且firstWhere
派上用场:
$tasks = collect([...]);
$firstTask = $tasks->first();
$urgentTask = $tasks->firstWhere('priority', 'urgent');
- keyBy():您有一个用户集合,并且想要通过他们唯一的 ID 对它们进行索引以便快速访问。
keyBy
解决方案是:
$users = collect([...]);
$indexedUsers = $users->keyBy('id');
- filter():您有来自 API 的订单集合,并且想要过滤掉已取消的订单。此
filter
方法非常适合此目的:
$orders = collect([...]);
$validOrders = $orders->filter(function ($order) {
return $order->status !== 'canceled';
});
- transform():您有一个任务集合,并且想要以某种方式修改每个任务。
transform
允许您将回调应用于每个项目以替换它:
$tasks = collect([...]);
$tasks->transform(function ($task) {
return $task->name . ' - ' . $task->priority;
});
现在就这些了,这些方法提供了简便性和灵活性,在使用 Laravel 应用程序时非常有用。