How to handle Undefined Offset in laravel?

vs_lala picture vs_lala · Apr 12, 2015 · Viewed 58.5k times · Source

I am getting this error when I land on the page after logging in:

ErrorException in compiled.php line 11573: Undefined offset: 0 (View: C:\xampp\htdocs\campusguru\resources\views\home.blade.php)

I know that the cause of this error is the empty variable that I passed to the view.

I have already tried:

if(isset($blog)) { do something }

and in blade view as:

{{ $blogs[0]->title or '' }}

Is there anyway I could handle this error. Or is there a better way of doing it?

Answer

 iisurge picture iisurge · Apr 12, 2015

try the following:

{{ isset($blogs[0]) ? $blogs[0]->title : '' }}

If your using a foreach to get every $blog->title use

@foreach ($blogs as $blog)
  {{ $blog->title }}
@endforeach