Chartjs-How to display data by current month and display no data message if data not exists

0πŸ‘

βœ…

I think i already solved this by using if else condition, and then using isEmpty() to check if the collection is empty or not, if it’s not empty, then run the foreach. Like this :

        if($achieveDaily->isEmpty()){
        $labels1[] = [];
        $plan1[] = [];
        $actual1[] = [];
    }else{
        foreach($achieveDaily as $ad){
            $labels1[] = Carbon::parse($ad->tgl)->format('j');
            $plan1[] = $ad->plan;
            $actual1[] = $ad->actual;
        }
    };

Thank you for everyone who tried to help me! Appreciated it!

0πŸ‘

You can use function whereMonth in laravel

DailyProduction::whereMonth('created_at', Carbon::now()->month)
            ->get();

0πŸ‘

So if you want to display data by current Month, can use whereDate() function. Why NOT combine whereMonth() and whereYear() together?

They will run separate query for just filtering specific month, and specific year and combine it.

So better query = better performance. Here’s example :

$dailyProduction = DailyProduction::whereDate('tgl', 'like', Carbon::now()->format('Y-m') . '%')->orderBy('tgl')->get();

$labels = [1, 2, ...]; // Basically anything to your graph labels, i assume you want to show daily
$plan = $actual = [];

foreach($dailyProduction as $daily) {
  $plan[] = $daily->plan;
  $actual[] = $daily->actual;
}

At your graph, when no data is there, just keep it blank. Or use blade @if @else

@if(empty($dailyProduction))
   <p>No Data</p>
@else
   // Your Graph
@endif

At your <script>. I assume rest of your const data is right

var labelsL1    = {!! json_encode($labels) !!};
var plan        = {!! json_encode($plan) !!};
var actual      = {!! json_encode($actual) !!};

Leave a comment