Argument 2 passed to App\Models\Thread::scopeFilter() must be an instance of App\Models\ThreadFilters, instance of App\Filters\ThreadFilters given

Posted 4 months ago by MartinZeltin

I am trying to implement the Filters from the "Let's build a Laravel forum" series here at Laracasts. But I keep getting this error.

Argument 2 passed to App\Models\Thread::scopeFilter() must be an instance of App\Models\ThreadFilters, instance of App\Filters\ThreadFilters given

The idea is that you can filter the results like so

  ../public/threads?by=Martin&popular=1&limit=10

Here is App\Filters\Filters.php

namespace App\Filters;
use Illuminate\Http\Request;

abstract class Filters
{
    protected $request;
    protected $builder;
    protected $filters = [];

    public function __construct(Request $request) {
        $this->request = $request;
    }

    public function apply($builder) {
        $this->builder = $builder;

        foreach ($this->getFilters() as $filter => $value) {
            if (method_exists($this, $filter)) {
                $this->$filter($value);
            }
        }

        return $this->builder;
    }

    public function getFilters() {
        return array_filter($this->request->only($this->filters));
    }
}

And here is the App\Filters\ThreadFilters.php

namespace App\Filters;

class ThreadFilters extends Filters
{
    protected $filters = ['by'];

    protected function by($username) {
        return $this->builder->where('username', $username);
    }
}

And then I call it from a controller like this

    use App\Models\Thread;
    use App\Filters\ThreadFilters;

    public function index(Request $request, ThreadFilters $filters)
    {
        return Thread::filter($filters)->get();
    }

Thread model looks like this

public function scopeFilter($query, ThreadFilters $filters)
{
    return $filters->apply($query);
}

My routes look like this

    Route::get('home', '[email protected]');

Please sign in or create an account to participate in this conversation.