1

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?

4 Answers 4

3

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

1

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.

Comments

0

$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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.