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

1

I need to search for users based on some filter attributes.

I have the contacts table:

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

The groups table:

id | grupo
 1 | grupo1
 2 | grupo2

And the table contact_group :

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

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

For the time being my code looks 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)                
    }

You were trying to use Join and SELECT within WHERE but did not work.

You will have several groups.

    
asked by anonymous 10.05.2016 / 22:24

1 answer

1

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

See:

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:

11.05.2016 / 04:33