Search code examples
phplaravelfiltereloquenturl-parameters

Setup Laravel Eloquent URL parameter based model filtering


I am building a RESTful API with Laravel and I am trying to develop a feature, which allows to send complex queries based on URL paramters to my database models.

I found a promising repository, which seems to implement the wanted functionality. https://github.com/heroicpixels/filterable

I struggle with understanding the wrapper and traits. I extended my model like mentioned in the documentation class Event extends Filterable {}. But I don't know how to properly implement the FilterableTrait and FilterableWrapper.

When I place use FilterableTrait inside my class, I get an error saying

Heroicpixels\Filterable\Filterable and Heroicpixels\Filterable\FilterableTrait define the same property ($filterable) in the composition of App\Event. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed

Currently my Event model looks like this

<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Carbon\Carbon;
use Heroicpixels\Filterable\Filterable;

class Event extends Filterable {

    /*
    use FilterableTrait;
    */

    protected $dates = ['deleted_at','starts_at','ends_at'];

    protected $fillable = [
        'deleted_at',
        'locale',
        'sports_id',
        'starts_at',
        'ends_at',
        'locations_id',
        'creators_id',
        'capacity',
        'attendees',
        'information',
        'level',
        'price',
        'lat',
        'lng'
    ];

    protected $hidden = ['created_at','updated_at','deleted_at'];

    public function creator() {
        return $this->hasOne('App\User','id','creators_id');
    }


    public function scopeFuture($query)
    {
        return $query->where('starts_at', '>=', Carbon::now());
    }

    public function scopeFreespots($query)
    {
        return $query->where('capacity', '>', 'attendees');
    }
}

What am I missing? How can I implement the Trait and the Wrapper so my URL parameters are used as query params? Thanks a lot for ur help!


Solution

  • As far as I can understand you have to choose just one method (out of three).

    You are trying to extend Filterable class AND use the trait. If you want to use the trait method you have to extend Eloquent class.

    It's probably best to extend the Filterable class as this method is also used in the documentation.