skip to Main Content

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

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. In PHP8 or Larvel 8
    simple use this one

    <h2>{{ $item->category->category_name ? 'no category' }}</h2>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search