skip to Main Content

In a laravel blade in third line of this code I want to check if parent_id exists in id column or not
please help me!
I’m using laravel 9

@if ($category->parent_id == 0)
no parent
@if ($category->parent_id)
no parent
@else
{{ $category->parent->name }}
@endif

I corrected it this way:

  @elseif (empty($category->parent))

3

Answers


  1. Balde:

    you can use the empty() to check if empty.

    @if ($category->parent == 0)
    no parent
    @elseif (empty($category->parent))
    <p>no parent</p>
    @else
    {{ $category->parent->name }}
    @endif
    

    or ?? operator

    {{ $category->parent_id ?? 'no parent' }}
    

    You can use the is empty in twig as below:

    {% if category is empty %}
      <p> No parent </p>
    {% endif %}
    
    Login or Signup to reply.
  2. You can try by using isset() function

    @if ($category->parent_id == 0)
    no parent
    @if (!isset($category->parent_id))
    no parent
    @else
    {{ $category->parent->name }}
    @endif
    
    Login or Signup to reply.
  3. Using exists() function for parent()

    Not that exists function works just with single relations (belongsTo, hasOne)

    // This will run SQL query // returns boolean 
    $category->parent()->exists(); // Don't forget parentheses for parent()
    

    If you want to save performance and not calling sql query

    count($category->parent); // returns 0 if not exist
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search