1

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.

1 Answer 1

1

You can use the query builder when method.

Using a conditional clause, you can write your code sample like this:

$company = Company::query()
    ->where('code', 'LIKE', '%' . request('search') . '%')
    ->orWhere('description', 'LIKE', '%' . request('search') . '%')
    ->orWhere('email', 'LIKE', '%' . request('search') . '%')
    ->with([
        'user' => function ($query) {
            $query->select('id', 'name', 'email');
        }
    ])
    ->when(
        request()->has(['field', 'direction']),
        fn($query) => $query->orderBy(request('field'), request('direction'))
    )
    ->paginate(5);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.