Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i find only deleted rows in Laravel?

Tags:

php

laravel

I'm using SoftDeletesin my projects, which is recognized as deleted_at in database table, I want to search and find only deleted rows.

Here is my controller code

 public function trashedJobSearch(Request $request)
{
    $search = $request->get('search');
    $jobs = Jobs::select('id', 'company_name', 'position_name', 'job_description','deleted_at', 'created_at', 'expire_date', 'status')
        ->where(DB::raw('lower(company_name)'), 'like', '%' . mb_strtolower($search) . '%')
        ->orWhere(DB::raw('lower(position_name)'), 'like', '%' . mb_strtolower($search) . '%')
        ->where('deleted_at', '!=', null)
        ->paginate(10);

    return view('/trashed', compact('jobs'));
}

I tried to use onlyTrashed() but it's not working either.

like image 996
Rasimoghlu Avatar asked Dec 04 '25 03:12

Rasimoghlu


2 Answers

As you have orWhere you need to use a grouping and also onlyTrashed

Jobs::select('id', 'company_name', 'position_name', 'job_description','deleted_at', 'created_at', 'expire_date', 'status')
  ->where(function ($query) use ($search) {
        $query->where(DB::raw('lower(company_name)'), 'like', '%' . mb_strtolower($search) . '%')
              ->orWhere(DB::raw('lower(position_name)'), 'like', '%' . mb_strtolower($search) . '%');
   })->onlyTrashed()
     ->paginate(10);
like image 166
Luis Montoya Avatar answered Dec 05 '25 19:12

Luis Montoya


The onlyTrashed() method should work for you. Docs for Laravel deleted entries. I have seen times where adding the raw select statement screws it up though.

Take out the extra bits with the select and DB::raw and then add them in after you have what you need. Start with the simplest:

$testOfDeletedOnlyJobs = Jobs::onlyTrashed()->get();

From here, add in the other parts of your query to see where and why it fails. If the above gives you nothing, perhaps there are no deleted records?

like image 23
Watercayman Avatar answered Dec 05 '25 21:12

Watercayman