Samuel Dauzon
Samuel Dauzon

Reputation: 11324

Laravel Eloquent Undefined offset: 0

I use Eloquent in order to get price of my product in the database. Here is my code :

$this->record = DB::select('select * from get_price(?);', array($product_name));
$this->price = $this->record[0]->price;

I'm sure to get one price with this query. But when I execute my code I get the following error :

Undefined offset: 0 in line 2

PHP don't find $this->record[0]. So, I decided to use the following code :

$this->record = DB::select('select * from get_price(?);', array($product_name));
var_dump(isset($this->record[0]));
foreach ($this->record as $key => $value) {
    var_dump($key);
    var_dump($value);
    var_dump($value->price);exit();
}
$this->price = $this->record[0]->price;

And I get :

// var_dump(isset($this->record[0]));
bool(true)

// var_dump($key);
int(0)

// var_dump($value);
class stdClass#2059 (2) {
  public $price =>
  string(2) "1"
  public $currency =>
  string(3) "USD"
}

// var_dump($value->price);exit();
string(2) "1"

I don't know why I can't access $this->record[0] but in a foreach of $this->record array I can access to the 0 index.

I'm using Laravel 4.2.

Upvotes: 0

Views: 3782

Answers (2)

zhekaus
zhekaus

Reputation: 3194

$this->record is not an array but a collection. Therefore you can't get an item using $this->record[0].

In order to get an array you can call method all() of the Illuminate\Database\Eloquent\Collection.

This will work:

$r = $this->record->all();
dd($r[0]);

Upvotes: 2

Basit
Basit

Reputation: 971

You can do this

$this->record = DB::select('select * from get_price(?);', array($product_name));
$this->price = collect($this->record)->first()->price;

It will only work if query fetches any record.

Upvotes: -1

Related Questions