0

I have this code

<?php

declare(strict_types=1);

namespace Voucher\Api\Store\Database\Repository;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder as QBuilder;

abstract class AbstractBaseRepository
{
    protected Model $model;

    public function __construct(Model $model)
    {
        $this->model = $model;
    }
//this function is called to get one Model or query/result
    public function query(): Builder|QBuilder
    {
        return $this->model::query();
    }
//this function come from other file
    public function findByKey(string $key): ?array
    {
        $apiKey = $this->query()
            ->where('key', $key)
            ->get()
            ->first();

        return $apiKey?->toArray();
    }
}

but phpstan say me

Cannot call method first() on array<Illuminate\Database\Eloquent\Builder|Illuminate\Database\Query\Builder>|Illuminate\Support\Collection

and yes Illuminate\Database\Eloquent\Builder say it can return an array even if it never happen

How can I do to avoid this error?

I cannot just put the tag to ignore error

  • 3
    `->get()->first()` gets all of the results where `key = $key`, which returns a collection, then returns the first result from that. It would be less work and code to just do `->first()` – aynber Apr 14 '23 at 15:33

0 Answers0