Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joyjas77's avatar

Best way to access a value from DB::select output

Hi,

Sorry complete re-write including title of this discussion as I figured out a method of solving original error, now just looking for best practice.

I've got the following code that gives me the id of a street address

$address = DB::select('SELECT roundsDetails.id FROM roundsDetails
        INNER JOIN streets ON roundsDetails.streetsId = streets.id
        WHERE streets.id = 307 AND roundsDetails.streetNumber = 21');

if I dump the output I get this

array (size=1)
  0 => 
    object(stdClass)[259]
      public 'id' => int 8659

I want to use the 8659 to be persisted in a database, but not sure if this way is the best

$complaint->complaintAddressId = $address[0]->id;

Any other ways you would tackle this?

0 likes
4 replies
thepsion5's avatar

You can use the pluck() method to retrieve a single value instead of the entire row. For example:

$addressId = DB::select(/* query */)->pluck('id'); //might be `roundsDetails.id`, I'm not positive
$complaint->complaintAddressId = $addressId;
joyjas77's avatar

Thanks for suggestion, but just tried it as below with roundsDetails.id and id as shown below

$address = DB::select('SELECT roundsDetails.id FROM roundsDetails
        INNER JOIN streets ON roundsDetails.streetsId = streets.id
        WHERE streets.id = ? AND roundsDetails.streetNumber = ?', [$street_id, $house_number])->pluck('roundsDetails.id');
        dd($address);

I get the following error with both

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR) 
Call to a member function pluck() on array
thepsion5's avatar
Level 25

Ah, DB::select() executes a select query without using the query builder. In that case the simplest thing would be this:

$address = DB::selectOne(/* query */);
$complaint->complaintAddressId = $address->id;
1 like
joyjas77's avatar

Thanks thepsion5,

That makes it look much cleaner and nicer.

Please or to participate in this conversation.