Home > OS >  How to check collection empty or not in Laravel 8
How to check collection empty or not in Laravel 8

Time:05-31

Hi this is my controller

public function reportDetail(Request $request)
   {
       $p_report = Report::office()->where('created_at','>=',Carbon::now()->subdays(60))->first(['column_thirteen', 'column_fourteen']);
       return view('acland.report.report_detail', $data);
   }

This is my view code

@if ($p_report->column_thirteen !== Null)
<td style="border: 1px solid black"  id="column_one">{{ $p_report->column_thirteen}}
<input type="hidden" name="column_one" value="{{$p_report->column_thirteen}}"></td>
@else
<td style="border: 1px solid black" ><input type="text" name="column_one" id="column_one"  style="min-width: 100px"></td>
@endif

When I try this I got Trying to get property 'column_thirteen' of non-object (View: C:\wamp64\www\report-management\resources\views\acland\report\type\rent_certificate.blade.php)

Please help me How Can I check if data empty or not?

CodePudding user response:

There's some methods you can try:

add an !empty() check:

@if (!empty($p_report))
   // code if not empty
@else
   // code if empty
@endif

Or add an isset() check:

@if (isset($p_report))
   // code if not empty
@else
   // code if empty
@endif

Do a count:

@if ($p_report->count() != 0)
   // code if not empty
@else
   // code if empty
@endif

CodePudding user response:

$p_report = Report::office()->where('created_at','>=',Carbon::now()->subdays(60))
->first(['column_thirteen', 'column_fourteen']);// return model or null

you can check it same as :

if (!$p_report) {
   // Do stuff if it doesn't exist.
}
  • Related