Laravel - Search if there is a relation in the many-to-many table

Asked

Viewed 182 times

1

I need to search users according to some filter attributes.

I have the table contacts:

id | nome | email
 1 | asd  | [email protected]
 2 |teste | [email protected]

The table groups:

id | grupo
 1 | grupo1
 2 | grupo2

And the table group contact:

id | id_grupo | id_contato
 1 |    1     |     1
 2 |    1     |     2
 3 |    2     |     1

In the search system form I list in checkbox (to choose as many as you want) all groups of the table. And I need to use this group filter.

For now my code is like this:

public function search(Request $request){
        $grupo = $request->grupo;

        $callbackSearch = function ($query) use($request){
            $campos = ['nome', 'sexo', 'email'];
            foreach ($request->only($campos) as $campo => $valor){
                $valor && $query->where($campo, 'like', $valor);
            }

        };

        $request = Contato::where($callbackSearch)->paginate(15);

        return view('people.list')
            ->with('r', $request)                
    }

I was trying to use Join and SELECT inside WHERE but it didn’t hurt.

Will have several groups.

  • The question I answered today solves your problem

  • http://answall.com/questions/127252/howto obtain registrations-of a tabular -when n%C3%A3o-h%C3%A1-relationship-with-another-table

  • Hi, I’d like you to feedback if that’s solved the problem

1 answer

1


I answered a question similar to that here today. You should use the method whereHas, to search the groups related to this user.

Behold:

public function search(Request $request)

{

    $callbackSearch = function ($query) use($request) {

        $campos = ['nome', 'sexo', 'email'];

        foreach ($request->only($campos) as $campo => $valor){
            $valor && $query->where($campo, 'like', $valor);
        }

        $grupos = $request->get('grupos');

        // Só executa a query se grupos tiver algo

        $grupos && $query->whereHas('grupos', function ($query) use($grupos)
        {
            // Creio que o grupo seja um array, já que é N para N

            $query->whereIn('id', $grupos);
        });

    };

    $request = Contato::where($callbackSearch)->paginate(15);

    return view('people.list')
        ->with('r', $request)                
}

Related:

  • Vlw, thanks! It worked, but I didn’t quite understand the part of: '$value &&...'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.