Search code examples
phpjsonlaravelintersection

Laravel eloquent query: create scope to check for column with values intersecting with static list of values?


I have a static list of valid values, e.g. $valid = ['one','two'],
and a column (e.g. types) in my model with multiple values (casts to array).

I could check if they intersect: array_intersect($model->types, $valid)

Can I create a scope that includes only the models that intersect?


Solution

  • I think you can with the orWhereJsonContains function, something like that:

    public function scopeNameIt(Builder $query,$array): void //pass the array as a parameter to the scope
     {
       $query->where(function($query) use ($array)){
          foreach($array as $element){
             $query->orWhereJsonContains('types',element);
          }
       }
     }
    

    You can read about it in the documentation

    Accorded to the documentation you can pass the array as well to the whereJsonContains function

    public function scopeNameIt(Builder $query,$array): void //pass the array as a parameter to the scope
     {
       $query->WhereJsonContains('types',$array);
     }