Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 964
panthro Avatar asked Dec 02 '16 12:12

panthro


1 Answers

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.

like image 128
Antonio Carlos Ribeiro Avatar answered Oct 21 '22 06:10

Antonio Carlos Ribeiro