Home > Software engineering >  Local scopes in Laravel Model didn't work
Local scopes in Laravel Model didn't work

Time:02-05

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.

CodePudding user response:

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.

  •  Tags:  
  • Related