Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Schema::create('prices', function (Blueprint $table) {
            $table->id();
            $table->string('openprice')->nullable();
            $table->string('closeprice')->nullable();
            $table->string('highprice')->nullable();
            $table->string('lowprice')->nullable();
            $table->timestamps();
        });

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading