ignisrzeus
6 months ago
1965
14
Laravel

Using WhereJsonContains with an array

Posted 6 months ago by ignisrzeus

Good day Laracasts! Would just like to know if there's a correct way of doing this.

Below is my code for my axios:

   axios.get("/api/user", {
                params:{
                    positions: ["Project Execution Head"]
                }
            }).then(response => {
                console.log(response.data.data);
            });

Below is my code in the index of my UserController

 $users = User::query();
        if($request->get('positions')){
            $positions = $request->get('positions');
            foreach($positions as $position){
                $users->whereJsonContains('positions', ['name' => $position])->get();
            }
        }
        return UserResource::collection($users->get());

Here is a sample of what Positions look like in the database (A user may have many positions, as they can be officers in charge)

[{"name":"Project Execution Head","job_level":"1A"}]

In that example above, i would have no problems in getting all of the users with a position of "Project Execution Head". However, things get a bit tricky if i add another element in the array, i,e:

   axios.get("/api/user", {
                params:{
                    positions: ["Project Execution Head", "Some Other Position"]
                }
            }).then(response => {
                console.log(response.data.data);
            });

If I add another element to the array, the query will return an empty collection instead, not even saving the users where their position is Project Execution Head. So my question here is:

  1. Am i allowed to combine WhereJsonContains and WhereIn? I tried this myself but i cant seem to make it work. I think this is the best approach to this problem but I can't make it work myself.

  2. Is my initial implementation correct? Am i just missing a few bits of information to make this work?

Thank you laracasts.

Please sign in or create an account to participate in this conversation.