Have you tried with a conditional clause like here: https://laravel.com/docs/8.x/queries#conditional-clauses
User::where('name', 'LIKE', '%'.$request->search.'%')
->when(true, function($query) {
return $query->withTrashed();
})
->orderBy($order, $direction)
->paginate(10)
->withQueryString()
->through(function ($user) {
return [
'id' => $user->id,
'profile_photo_url' => $user->profile_photo_url,
'name' => $user->name,
'username' => $user->username,
'email' => $user->email,
'created_at' => $user->created_at,
'updated_at' => $user->updated_at,
'email_verified_at' => $user->email_verified_at,
];
})
]);
ofc replace true with your check. Here is an example as well https://laraveldaily.com/less-know-way-conditional-queries/