panthro
panthro

Reputation: 24061

newQuery() in Laravel

Whats the difference between doing:

$model = User::newQuery();
$model->published(1);
$model->get();

And:

$model = User;
$model = $model->published(1);
$model = $model->get();

I know with the second example you have to assign the call back to the model. But is there any difference to these?

Note, I'm not chaining as there would be some conditions between checking if it should be published or not etc.

Upvotes: 8

Views: 22378

Answers (1)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

It depends on what published() is. Changing your code a bit:

$model = User::newQuery();
$model->where('published', 1);
$model->get();

or

$model = new User;
$model = $model->where('published', 1);
$model = $model->get();

Doing

Route::get('debug/model', function () {
    $model = new App\Data\Entities\User;

    $model = $model->with('gender');
    $model = $model->where('username', 'gigante');
    $model = $model->get();

    dd($model);
});

I got

enter image description here

The difference is that once instantiated, you'll have to do $model = $model->whatever(), because laravel is returning an instance of QueryBuild and you now have an instance of Eloquent.

So, not much different, because when Laravel is not able to execute what you need in the model, it goes right to the QueryBuilder, by executing newQuery(), so your codes are doing basically the same.

Backing to your code,

$model->published(1);

If Model doest not find that method, so it will try newQuery(), so, maybe.

Upvotes: 4

Related Questions