Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do laravel eloquent table with joins, orwhere and pagination correctly?

This is my original code where i display all data for team users.

 $data = Teamuser::join('teams', 'teams.id', '=', 'team_user.team_id')
            ->join('users', 'users.id', '=', 'team_user.user_id')
            ->get(['users.name as username','teams.name','users.email','team_user.role','team_user.id','team_user.user_id','team_user.team_id']);

However, since im developing a search function for the table. I try adding orwhere to the function.

$data = Teamuser::join('teams', 'teams.id', '=', 'team_user.team_id')
            ->join('users', 'users.id', '=', 'team_user.user_id')
            ->get(['users.name as username','teams.name','users.email','team_user.role','team_user.id','team_user.user_id','team_user.team_id'])
            ->where('users.name', 'like', '%'.$request->search2.'%')
            ->orWhere('teams.name', 'like', '%'.$request->search2.'%')
            ->orWhere('team_user.role', 'like', '%'.$request->search2.'%')
            ->orWhere('users.email', 'like', '%'.$request->search2.'%')->paginate(5);

But the search function doesnt work, how do i format the syntax in a correct way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m not sure you are using get() correctly, but i purpose you an alternative syntax

$data = Teamuser::select(['users.name as username','teams.name','users.email','team_user.role','team_user.id','team_user.user_id','team_user.team_id'])
            ->join('teams', 'teams.id', '=', 'team_user.team_id')
            ->join('users', 'users.id', '=', 'team_user.user_id')
            ->where('users.name', 'like', '%'.$request->search2.'%')
            ->orWhere('teams.name', 'like', '%'.$request->search2.'%')
            ->orWhere('team_user.role', 'like', '%'.$request->search2.'%')
            ->orWhere('users.email', 'like', '%'.$request->search2.'%')
            ->paginate(5);

Check if your join is correct, maybe you could use leftJoin() instead of join()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading