侧边栏壁纸
  • 累计撰写 168 篇文章
  • 累计创建 71 个标签
  • 累计收到 35 条评论

目 录CONTENT

文章目录

Laravel 集合中的 first() 和 firstWhere() 方法

神兵小将
2023-02-02 / 0 评论 / 22 点赞 / 184 阅读 / 2,118 字 / 正在检测是否收录...

1 使用 first() 方法

在这个例子中,我们将考虑一个多维数组。我们将看到如何使用 first() 进入集合。

假设我们在/app/Http/Controllers文件夹中有一个控制器文件 SiteController.php 。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SiteController extends Controller
{
    public function index()
    {
        $data = collect([
            ["id" => 1, "name" => "Sanjay", "email" => "sanjay@gmail.com"],
            ["id" => 2, "name" => "Vijay", "email" => "vijay@gmail.com"],
            ["id" => 3, "name" => "Ashish", "email" => "ashish@gmail.com"]
        ]);

        $first = $data->first();

        dd($first);
    }
}

输出

当我们执行这个代码片段时,我们会得到这样的东西——

2 使用 firstWhere() 方法

我们将看到如何使用 firstWhere() 进入集合。

firstWhere() 方法表示我们将使用一些条件来获取值。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SiteController extends Controller
{
    public function index()
    {
        $data = collect([
            ["id" => 1, "name" => "Sanjay", "email" => "sanjay@gmail.com"],
            ["id" => 2, "name" => "Vijay", "email" => "vijay@gmail.com"],
            ["id" => 3, "name" => "Ashish", "email" => "ashish@gmail.com"]
        ]);

        $first = $data->firstWhere("email", "vijay@gmail.com");

        dd($first);
    }
}
$first = $data->firstWhere("email", "vijay@gmail.com");

输出
laravel-8-collection-get-first-row-value-using-first-method.webp
当我们执行这个代码片段时,我们会得到这样的东西——

另一个使用 firstWhere() 的例子,

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SiteController extends Controller
{
    public function index()
    {
        $data = collect([
            ["id" => 1, "name" => "Sanjay", "email" => "sanjay@example.com", "age" => 29],
            ["id" => 2, "name" => "Vijay", "email" => "vijay@gmail.com", "age" => 32],
            ["id" => 3, "name" => "Ashish", "email" => "ashish@sample.com", "age" => 25]
        ]);

        $first = $data->firstWhere("age", ">", 30);

        dd($first);
    }
}

$first = $data->firstWhere("age", ">", 30);

输出
firstWhere-method-in-laravel-8-collection-with-operator[1]

22

评论区