Thejaka Maldeniya
Thejaka Maldeniya

Reputation: 1076

Laravel: Applying model accessors through query builder

I'm trying to get a default Builder object for a model in Laravel 5.5.

I have tried using MyModel::getQuery() and MyModel::toBase() to get a default Builder result to be later chained. This was to facilitate a configurable starting point for the query. i.e. If a value is present for a where constraint, the starting point would be MyModel::where(). If not, then getQuery() or toBase().

The clauses applied later may be common to either path, hence the need for a default builder.

This seems to work, but not exactly as expected. If starting with where, model accessors get applied. If starting with getQuery() or toBase(), the accessors are not applied.

Is this by design, or a bug? Is there a better way to start a query chain, than using a dummy clause such as where('column_1', 'LIKE', '%') or orWhere('column_2', ''), as it would only be a workaround and also I don't believe this would be very efficient?

Upvotes: 0

Views: 1015

Answers (1)

kjames
kjames

Reputation: 656

Have you tried using query() ?

$model = MyModel::query();

if (example == 'test') {
    $model = $model->where('column', 0);
}

if (example2 == 'test2') {
    $model = $model->where('another_column', 'test');
}

$model = $model->get();

Reference: https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Model.html#method_query

Upvotes: 1

Related Questions