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?
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);
}