How can i find only deleted rows in Laravel?

Viewed 1644

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.

4 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);

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?

You can try this.

In your Model-

use Illuminate\Database\Eloquent\SoftDeletes;

class ModelName extends Model
{
    use SoftDeletes;
}

To get only deleted rows

$search = $request->get('search');
$data = App\ModelName::onlyTrashed()
                ->where('id', $search)
                ->get();
Related