cracker182 cracker182 - 4 days ago 6
PHP Question

Laravel ORM created_at Field

i have two Models


  1. Station

  2. Price



I have set up the relations

class Station extends Model
{
protected $keyType = "string";
public $incrementing = false;

public function prices()
{
return $this->hasMany('App\Price');
}

public function latestPrice()
{
return $this->hasOne('App\Price')->orderBy('created_at', 'desc');
}
}


class Price extends Model
{
protected $visible = ['created_at'];
public function station()
{
return $this->belongsTo('App\Station');
}
}


I fetch the Price, which belongs to a Station with

$stations = Station::all();
$now = new Carbon();

foreach ($stations as $station) {
$lastPrice = $station->latestPrice;
$t = $lastPrice->created_at;
$difference = $now->diffInMinutes($test);
if ($difference > 4) {
//$this->saveNewPrice($station->id);
}
}


but i get the Error "Trying to get property of non-object". I don't know why this is the case.
If I dd
$lastPrice->created_at
i get the correct results, but if i try to use them i get the error.

Could anyone help me to solve this error?

Thank you so much,
c

Answer

There may be chances that for some station there is no price so it's better to wrap that part in if clause as:

foreach ($stations as $station) {
    $lastPrice = $station->latestPrice;
    if(lastPrice) {
        $t = $lastPrice->created_at;
        $difference = $now->diffInMinutes($test);
        if ($difference > 4) {
            //$this->saveNewPrice($station->id);
        }
    }
}
Comments