您从未使用过的 10 种 Laravel 集合方法

36 篇文章 0 订阅
10 篇文章 0 订阅

在本文章中,我们将更深入地探讨我们都使用的 Laravel 的各个部分,以揭示我们可以在下一个项目中使用的功能和特性......如果我们了解它们就好了!

以下是一些鲜为人知的收集方法,在各种实际场景中非常有用:

  1. macro():这允许您向 Laravel 集合添加可在任何集合实例上使用的自定义方法:

use Illuminate\Support\Collection;

Collection::macro('customMethod', function () {
    // Your custom method logic
});

$collection = collect([...]);
// use on any collection object
$result = $collection->customMethod();
  1. concat():假设您有两个来自不同来源的用户集合,并希望将它们合并为一个集合。您可以concat为此目的使用:
$usersFromDatabase = User::where(...)->get();
$usersFromApi = collect([...]);

$combinedUsers = $usersFromDatabase->concat($usersFromApi);
  1. pad():您有一个任务集合,但您想确保它始终包含最少数量的元素。pad如有必要,您可以使用它来添加虚拟任务:
$tasks = collect([...]);

$paddedTasks = $tasks->pad(10, 'Dummy Task');
  1. shuffle() & random():假设您有一个测验应用程序,并且想要打乱问题的顺序。您可以使用shuffle它来实现此目的。此外,如果您要从集合中随机选择一个问题,您可以使用random
$questions = collect([...]);

$shuffledQuestions = $questions->shuffle();
$randomQuestion = $questions->random();
  1. 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'],
] */

  1. partion():假设您有一群学生,您想根据他们的成绩(通过或不通过)将他们分成两组。partition这很容易:

$students = collect([...]);

list($passingStudents, $failingStudents) = $students->partition(function ($student) {

    return $student->grade >= 60;

});

  1. first()firstWhere():您有一个任务集合,并且想要检索第一个任务或满足特定条件的第一个任务。first并且firstWhere派上用场:

$tasks = collect([...]);

$firstTask = $tasks->first();

$urgentTask = $tasks->firstWhere('priority', 'urgent');

  1. keyBy():您有一个用户集合,并且想要通过他们唯一的 ID 对它们进行索引以便快速访问。keyBy解决方案是:

$users = collect([...]);

$indexedUsers = $users->keyBy('id');

  1. filter():您有来自 API 的订单集合,并且想要过滤掉已取消的订单。此filter方法非常适合此目的:

$orders = collect([...]);

$validOrders = $orders->filter(function ($order) {

    return $order->status !== 'canceled';

});

  1. transform():您有一个任务集合,并且想要以某种方式修改每个任务。transform允许您将回调应用于每个项目以替换它:

$tasks = collect([...]);

$tasks->transform(function ($task) {

    return $task->name . ' - ' . $task->priority;

});


现在就这些了,这些方法提供了简便性和灵活性,在使用 Laravel 应用程序时非常有用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rorg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值