Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ronyamin's avatar

Pagination issue with Search query

Hi,

I want to add the pagination in my search query. But I a confused how to use pagination along with Join tables.

Here is my query.

$user = CareerSolution::where ( 'subject', 'LIKE', '%' . $q . '%' )
                      ->where('career_solutions.topic_category_id', '=', $c)
        ->join('role_users' , 'role_users.user_id', '=', 'career_solutions.user_id')
        ->join('roles' , 'roles.id', '=', 'role_users.role_id')
        ->join('users', 'users.id', '=', 'career_solutions.user_id')
        ->join('categories', 'categories.id', '=', 'career_solutions.topic_category_id')
        ->orWhere ( 'career_solutions.user_id', 'LIKE', '%' . $q . '%' )
        ->orWhere ( 'career_solutions.id', '=', 'events.subject')
        ->orWhere('career_solutions.topic_category_id' ,'=', $category->id)
        ->orWhere ( 'career_solutions.user_id', '=', 'users.username')
       ->select('career_solutions.id as id','subject','users.id as user_id','username', 'profile_picture', 'role_id', 'optional', 'topic_category_id','categories.category')
         ->get ();
1 like
3 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@ruhulamin

You can easily use paginate() with joining tables. Noting wrong with that.

Try this in your controller-

$user = CareerSolution::where ( 'subject', 'LIKE', '%' . $q . '%' )
    ->where('career_solutions.topic_category_id', '=', $c)
    ->join('role_users' , 'role_users.user_id', '=', 'career_solutions.user_id')
    ->join('roles' , 'roles.id', '=', 'role_users.role_id')
    ->join('users', 'users.id', '=', 'career_solutions.user_id')
    ->join('categories', 'categories.id', '=', 'career_solutions.topic_category_id')
    ->orWhere ( 'career_solutions.user_id', 'LIKE', '%' . $q . '%' )
    ->orWhere ( 'career_solutions.id', '=', 'events.subject')
    ->orWhere('career_solutions.topic_category_id' ,'=', $category->id)
    ->orWhere ( 'career_solutions.user_id', '=', 'users.username')
    ->select('career_solutions.id as id','subject','users.id as user_id','username', 'profile_picture', 'role_id', 'optional', 'topic_category_id','categories.category')
    ->paginate(6);

To render the pagination link, you need to use following codes in the view-

{{ $user->links }}

Understand more flow of pagination here: https://laravel.com/docs/6.x/pagination

3 likes
ronyamin's avatar

Thank you sir. Really appreciated.

1 like
jeffreyvanrossum's avatar

You are not asking for this in particular, but I am going to share this anyway. If your search term variable ($q) comes from a GET-request, you will notice that this parameter is lost on the links that the pagination returns.

To add it, you can append to it like this:

{{ $user->appends(['q' => $q])->links() }}
1 like

Please or to participate in this conversation.