Home > database >  Foreign key is now null and when mapping through the data it say "Attempt to read property &quo
Foreign key is now null and when mapping through the data it say "Attempt to read property &quo

Time:11-09

I deleted a category which is an f-key of the items table. Now the view has an error saying 'Attempt to read property "category_name" on null'. How do I render a null foreign key?

I tried if-else:

@if({{$item->category->category_name}} === 'null')
  <h2>no category</h2>
 @else
  {{ $item->category->category_name}}
@endif

CodePudding user response:

Try this:

@if ($item->category)
    {{ $item->category->category_name }}
@else
    <h2>no category</h2>
@endif

Or simply

<h2>{{ $item->category?->category_name ?? 'no category' }}</h2>

CodePudding user response:

In PHP8 or Larvel 8 simple use this one

<h2>{{ $item->category->category_name ? 'no category' }}</h2>
  • Related