简体   繁体   中英

Local scopes in Laravel Model didn't work

I created new scope in Laravel's model and it didn't work at all. It seems invisible for the controller.

File test.php in Models:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
    public function scopeLatest(Builder $query, int $limit)
    {
        return $query
        ->select(['id', 'title', 'main_photo', 'area', 'price', 'city', 'short_desc'])
        ->whereIn('status', ['Dostepne', 'Zarezerwowane'])
        ->orderBy('id', 'desc')
        ->limit($limit)
        ;
    }
}

Controller file:

$flats = Test::latest(3)->get();

In the end, I'm reciving every record in database. When I delete get methode in controller, i'm recive no records. Whatever I write in scopeLatest it doesn't matter.

There is already a method named latest that exists on the Eloquent Query Builder; it is a public method so that is what you are calling directly. To be able to apply a scope (call a scope on the Builder) you would have to be calling a non existing or inaccessible (not visible) method which would make PHP call the __call method which would eventually be checking if a scope exists and then calling it.

Name your scope something else if you want to be able to apply it in the fluent fashion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM