Carol.Kar
Carol.Kar

Reputation: 5345

Laravel 5.5 - Parse result of db query

I am using Laravel Framework 5.5.26 and I am querying my db with the following call:

    $symbolsArray = DB::table('exchanges')
        ->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
        ->where('name', $exchangeName)
        ->get(array(
            'symbol',
        ));

If I var_dump($symbolsArray) I get the following output:

class Illuminate\Support\Collection#619 (1) {
  protected $items =>
  array(99) {
    [0] =>
    class stdClass#626 (1) {
      public $symbol =>
      string(7) "BCN/BTC"
    }
    [1] =>
    class stdClass#621 (1) {
      public $symbol =>
      string(8) "BELA/BTC"
    }
    [2] =>
    class stdClass#623 (1) {
      public $symbol =>
      string(7) "BLK/BTC"
    }
    [3] =>
    class stdClass#627 (1) {
      public $symbol =>
      string(8) "BTCD/BTC"
    }
    ...
  }
}

I am trying to get the $symbol like the following:

$symbolsArray[$key]['symbol']

However, I get the following error:

  Cannot use object of type stdClass as array

Any suggestions how to access the symbol from the query output?

Upvotes: 1

Views: 1758

Answers (4)

Leo Rams
Leo Rams

Reputation: 729

$symbolsArray is a collection and not an array. The get an array, you could pluck symbol from the collection $symbolsArray = DB::table('exchanges') ->join('markets', 'exchanges.id', '=', 'markets.exchanges_id') ->where('name', $exchangeName) ->pluck('symbol')->all(); or you could actually convert your collection to an array by $new_array = $symbolsArray->toArray()

Upvotes: 0

Matthias S
Matthias S

Reputation: 3553

The result of DB::table()->get() is always a Collection, whose attributes you access like variables within a PHP class with ->.

In your example, your $symbolsArray is not actually an array, you access the content with $symbolsArray[$key]->symbol.

Assuming that you are new to Laravel, I suggest you have a look at Laravel's built in ORM Eloquent. It makes working with Databases easy and straightforward, and if you dive a bit into Eloquent's Collections you will see that they make working with data a breeze.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

It's a collection of objects, not arrays. So you need to use this syntax to get property of an object in a collection:

$symbolsArray[$key]->symbol

If you need to get just symbols, use pluck() instead of get():

->pluck('symbol')->toArray()

Upvotes: 3

Aman Kumar
Aman Kumar

Reputation: 4547

Simple convert given output as an array like shown below

$symbolsArray = DB::table('exchanges')
        ->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
        ->where('name', $exchangeName)
        ->get(array(
            'symbol',
        ))->toArray(); // get data as array not object 

Upvotes: 1

Related Questions