How can do conditional statement to set data value to zero when fetch data not avaliable from database by laravel

i have one problem , i try to fetch data from database to show it on view page ..

when this data not ready in database , i dont want to show

attempt to read property on null or 404 not found

its migration table is as follow

Schema::create('prices', function (Blueprint $table) {

my fetch code is

        $now = CarbonImmutable::now();
        $MinuteAgo = $now->subMinute(70);
        $pricelist = Sell::whereBetween('created_at', [$MinuteAgo,$now])->orderBy('id','asc')->get();
        $priceHL = Sell::whereBetween('created_at', [$MinuteAgo,$now])->orderBy('price','asc')->get();

            $openprice = $pricelist->first()->price;
            $closeprice = $pricelist->last()->price;
            $highprice = $priceHL->last()->price;
            $lowprice = $priceHL->first()->price;

if data not ready in database , it get problem in view ,

i just want to show in view when data not ready , its value as zero ,

example ,

if data ready , $openprice = 0.0011 
if not ready , $openprice = 0

how can do it , can it be or not , i have low experience in data manipulation ,

my target achivement is not to distrub to view page , when no data , this will show error page .

Route::get('/candle',[App\Http\Controllers\ChartController::class, 'chart']);

if so , user interface will get trouble for users.

actually i try is to show candlestick chart on this view page , so if some minutes interval data not ready , the candle chart page will get error in display .

can someone help me .

>Solution :

All your data based on $pricelist so

if ($pricelist->isEmpty()) {
    $openprice = 0;
    $closeprice = 0;
    $highprice = 0;
    $lowprice = 0;
} else {
    $openprice = $pricelist->first()->price;
    $closeprice = $pricelist->last()->price;
    $highprice = $priceHL->last()->price;
    $lowprice = $priceHL->first()->price;

Leave a Reply