I have been trying to sort the table after fetching it from the database and I could able to sort and search but with a repetitive code. Can anyone help me with how to refactor this code?
if(request()->has(['field', 'direction']))
{
$company = Company::query()
->orwhere('code', 'LIKE', '%'.request('search').'%')
->orwhere('description', 'LIKE', '%'.request('search').'%')
->orwhere('email', 'LIKE', '%'.request('search').'%')
->orderBy(request('field'), request('direction'))
->with(['user' => function ($query) {
$query->select('id','name', 'email');
}])->paginate(5);
}
else
{
$company = Company::query()
->orwhere('code', 'LIKE', '%'.request('search').'%')
->orwhere('description', 'LIKE', '%'.request('search').'%')
->orwhere('email', 'LIKE', '%'.request('search').'%')
->with(['user' => function ($query) {
$query->select('id','name', 'email');
}])->paginate(5);
}
If the request has a field value and direction then it's executing a block or it's executing another block. How can I refactor the code in a single block?
Thanks in advance.