0

I created a very simple query but the laravel builder added additional query which I will like to remove.

\DB::enableQueryLog();
  App\Proj::whereNotNull('deleted_at')->paginate(20);
dd(\DB::getQueryLog());

The query that came out of it is as follows:

select * from `projs` where `deleted_at` is not null and `projs`.`deleted_at` is null

To get a good result, the query needed is:

select * from `projs` where `deleted_at` is not null

Without the 'and ...' in the query result statement.

3 Answers3

3

Your Proj model probably uses SoftDeletes Trait, thus the deleted_at is not null part is added by default.

Get the deleted ones like:

App\Proj::onlyTrashed()->paginate(20)

See here https://laravel.com/docs/8.x/eloquent#retrieving-only-soft-deleted-models

Tania Petsouka
  • 1,388
  • 1
  • 9
  • 20
2

don't use whereNotNull('deleted_at') because if you are using soft delete then laravel automatically run this

  • Thanks for the feedback, but how can I have a list of the deleted only? – Samuel Omopariola Feb 19 '21 at 17:01
  • This is one perfect answer as a query builder. Cause often 'null' can not be considered as all databases may not recognize it. so whereNotNull() is the right choice to check if the field is not 'null' – Mehedi Hassan Feb 19 '21 at 17:44
2

To get the soft deleted Proj entries use onlyTrashed()

\DB::enableQueryLog();
  App\Proj::onlyTrashed()->paginate(20);
dd(\DB::getQueryLog());

if you want to include the soft deleted ones in a query, use withTrashed()

App\Proj::withTrashed()->paginate(20);
N69S
  • 16,110
  • 3
  • 22
  • 36