lundi 4 décembre 2017

Laravel dynamic scope only works first time

I'm missing something with how the global scopes work in Laravel 5.5.

In my controller, index , I am passing filters into a getter:

public function index(SaleFilters $filters)
{
    return new SaleCollection($this->getSales($filters));
}

getSales:

protected function getSales(SaleFilters $filters)
{
    $sales = Sale::with('office')->filter($filters);

    return $sales->paginate(50);
}

protected function range($range)
{
    $dates = explode(" ", $range);
    if (count($dates) == 2) {
        $this->builder = Sale::with(['office', 'staff']) 
            ->where('sale_date', '>=', $dates[0])
            ->where('sale_date', '<', $dates[1])
            ->orderBy('sale_date', 'desc');

        return $this->builder;
    }
    return false;
}

I have a scope setup in the sale model as such, which I would have thought would apply to the above filter automatically ? If not, do I have to reapply the same scope, duplicating the scope code in the filter ?

protected static function boot() 
{
    parent::boot();

    $user = Auth::user();
    if (($user) && ($user['office_id'])) {
        return Sale::ofOffice($user['office_id'])->get();
    } 
}

public function scopeOfOffice($query, $office) 
{
    return $query->where('office_id', $office);
}

So basically, IF the user has an office_id applied, it should apply the ofOffice scope, therefore it should only ever return the sales that apply to that office_id.

Basically it works on page load via axios GET request

Route::get('/sales', 'SalesController@index')->middleware('auth:api');

axios
    .get('api/sales/?range=" + this.rangeFilter)

rangeFilter is basically a start and end date passed into the above filter query.

Can anyone shed some light on how the scopes really work or if anything is obvious as to why its not always working? As I said, it works on page load where I provide default values for the rangeFilter, however when I change those days and it refetches via the same axios call, it seems to not be applying the scope, and I get ALL results instead of where office_id = 'x'

As far as i'm concerned, the range filter above would be executing on the first page load as well, so not sure why it would apply there, and not afterwards.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire