Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Laravel 10 criteria no longer work? #799

Open
DeGraciaMathieu opened this issue Oct 26, 2023 · 2 comments
Open

Laravel 10 criteria no longer work? #799

DeGraciaMathieu opened this issue Oct 26, 2023 · 2 comments

Comments

@DeGraciaMathieu
Copy link

Hi,

Is anyone using the criteria in Laravel 10 ?

It appears that the criteria are no longer being applied to the model.

This method is located in the BaseRepository class, which is responsible for instantiating a new instance of the model:

public function makeModel()
{
    $model = $this->app->make($this->model());

    if (!$model instanceof Model) {
        throw new RepositoryException("Class {$this->model()} must be an instance of Illuminate\\Database\\Eloquent\\Model");
    }

    return $this->model = $model;
}

This approach seems unusual because instantiating the model in this way doesn't allow us to apply a where clause.

It's somewhat equivalent to doing this :

app(User::class)->whereNotNull('verified_at')->get();

In this example, app returns an instance of the model, not of EloquentBuilder. I don't understand how this approach still works as intended.

The only solution I've found is to implement the makeModel method in my repository class, which is not ideal :

class UserRepositoryEloquent extends BaseRepository implements UserRepository
{
    public function model()
    {
        return User::class;
    }

    public function makeModel()
    {
        $model = $this->app->make($this->model());

        return $this->model = $model->query();
    }

    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }
}

Does anyone have a better idea?

@IgorNIT
Copy link

IgorNIT commented Nov 4, 2023

The same issue with Laravel 9.5. Criteria are not working for methods - all(), get(), paginate(). Works only with limit();

@IgorNIT
Copy link

IgorNIT commented Nov 6, 2023

The solution with makeModel() is not Ok because that function is used in resetModel() and it doesn't reset the model. If you use the repository class twice it will have the previous query parameters.
My HOT fix is calling the custom reset() method before pushCriteria().

 public function reset()
    {
        $this->model = $this->app->make($this->model())->query();
        return $this;
    }

$products = $productsRepository->reset()->pushCriteria(new Search($params))->paginate();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants