Search code examples
laravellaravel-query-builder

Is there a way to only return the ID from this Laravel Query


I have run a query to get my specific needs but it's returning a whole bunch of array, Is there a way to get only the specific column i needed?

This is what i am trying

 $datas = DB::table('tableA')
                    ->select('tableA.id')
                    ->rightJoin('tableB','tableA.id','=','tableB.tableAt_id')
                    ->where('tableB.active',1)
                    ->whereIn('tableB.status',$myArray)
                    ->get();

and the output is

Illuminate\Support\Collection {#1349 ▼
  #items: array:221 [▼
    0 => {#1327 ▼
      +"id": 2020010201
    }
    1 => {#1346 ▼
      +"id": 2020010202
    }
    2 => {#1343 ▼
      +"id": 2020011501
    }

I only want the ID. i tried toArray() but its the same


Solution

  • Use pluck.

    Your code should be.

    $datas = DB::table('tableA')
                        ->rightJoin('tableB','tableA.id','=','tableB.tableAt_id')
                        ->where('tableB.active',1)
                        ->whereIn('tableB.status',$myArray)
                        ->pluck('tableA.id');
    

    Read More about Pluck Method