skip to Main Content

I’m having trouble fetching records from a table that matches the data below:

$request->cardColor contains:

    0 => "White"
    1 => "Green"

I’d like to to fetch records from my cards table that exactly matches the data above to its colors column. A sample (array) entry in this column would be ["White","Green","Red","Blue"]

With this, I would like to be able to fetch entries with strictly White and Green values only. Hoping to be able to build a proper query for this.

Please feel free to ask clarification questions, and any help would be appreciated.

2

Answers


  1. If you want to get all records that have value of column colors contained in your entry array:
    DB::table('your_table')->whereIn('column_name', your_array)->get();

    Login or Signup to reply.
  2. You can combine the usage of whereJsonContains() and whereJsonLength() to achieve the desire result, for example:

    $colors = $request->cardColor;
    IlluminateSupportFacadesDB::table('cards')
        ->whereJsonContains('colors', $colors)
        ->whereJsonLength('colors', count($colors))
        ->get();
    

    The call to whereJsonContains() allows you to check whether the values inside the column exists or not, and the call to whereJsonLength() is necessary since you want the colors column to contain the exact same amount of elements as in $request->cardColors.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search