0

I have a model

I call it this way:

Sight::filter(['type'=>'menu']);

and in model:

public function scopeFilter($query,$params)
{
    return $query
        ->wherePublish(1)
        ->whereIn_special(1)
        ->latest()
        ->first();
}

when there is one or more records, it works normally.

but when database is empty I get an odd behavior:

with dd(Sight::filter(['type'=>'menu']))

or

$query
        ->wherePublish(1)
        ->whereIn_special(1)
        ->latest()
        ->first();
        dd($query);

I got this result:

enter image description here

But with

dd(
$query
            ->wherePublish(1)
            ->whereIn_special(1)
            ->latest()
            ->first();
)

I got Null so it is right!

how can I return Null? what is my wrong?

1 Answer 1

2

You shouldn't be calling first() inside of a scope - you are only meant to adjust the query by constraining it. You should call first() in your chain after applying the filter() scope. If you want to use the same syntax rather than chaining like that you would be best to define a custom static method.

public static function filter($params)
{
    return self::wherePublish(1)
        ->whereIn_special(1)
        ->latest()
        ->first();
]

Also note that in your example your scope accepts an argument (and you pass it one) but it isn't actually used in your code.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, what about take() and paginate() ? They are invalid like first() in scope?
take() is fine because again it's just adding constraints to the query. paginate() is not because like get() or first() it is actually performing the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.