A
A
Andrey Skripnik2022-02-03 15:56:42
Laravel
Andrey Skripnik, 2022-02-03 15:56:42

Is it necessary to split the local scope into two depending on the number of values ​​in the argument?

I would like to get opinions on how to write correctly / more correctly:

public function scopeByPartnerId($query, $partnerId)
{
    if (is_countable($partnerId)) {
        $query->whereIn('partner_id', $partnerId);
    } else {
        $query->where('partner_id', $partnerId);
    }
}

or

public function scopeByPartnerId($query, $partnerId)
{
    $query->where('partner_id', $partnerId);
}

public function scopeByPartnerIds(Builder $query, array $partnerIds)
{
    $query->whereIn('partner_id', $partnerIds);
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2022-02-03
@andreskrip

There is no “correct” in this matter and cannot be. It can be "more understandable for others" and "more supportive". For the second there is no difference, for the first I prefer this option:

public function scopeByPartnerId($query, int|array $partnerId)
{
    if (is_countable($partnerId)) {
        $query->whereIn('partner_id', $partnerId);
    } else {
        $query->where('partner_id', $partnerId);
    }
}

And, of course, in the class itself, a doc-block is described for this method, in which the correct types of arguments are also indicated.

S
Sergey delphinpro, 2022-02-03
@delphinpro

You don't have to share anything. You need to leave one method of multiple selection.

J
jazzus, 2022-02-03
@jazzus

Partner relationship? Then it is more correct to use the relationship methods
$partner->relations
whereHas, with etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question