Home > database >  how to check is there a value in the other column of table?
how to check is there a value in the other column of table?

Time:01-16

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

CodePudding user response:

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

CodePudding user response:

Balde:

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

@if ($category->parent_id == 0)
no parent
@if (empty($category->parent_id))
<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 %}

CodePudding user response:

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
  • Related