Code Worm
Code Worm

Reputation: 323

How to check if object key exists and is not null or if it is a certain value in a foreach loop in Laravel blade?

I have a foreach loop in blade where I am looping through an array of items, and some items has an additional key called validation_status which is either null or an object.

An example:

category: "Storage"
client_id: 6575
created_at: "2019-08-12 15:50:04"
created_by: 233
datasheet: null
deleted_at: null
description: "3erty"
energy_rating: 0
fk_item_type: 83
id: 369
item_model_id: 475
model_number: null
power_consumption: 3
searchable: 1
shared: 1
updated_at: "2019-11-09 17:59:04"
updated_by: 233
validated: 0
validation_status: null
vendor: null

category: "Network"
client_id: 6575
created_at: "2019-07-11 16:04:56"
created_by: 233
datasheet: null
deleted_at: null
description: "2we5"
energy_rating: 0
fk_item_type: 83
id: 357
item_model_id: 470
model_number: null
power_consumption: 55
searchable: 1
shared: 1
updated_at: "2019-11-07 10:29:57"
updated_by: 233
validated: 0
validation_status:
created_at: "2019-11-07 16:08:49"
id: 2
item_id: 357
item_type: "IT_Analysis"
message: null
name: "pending"
updated_at: "2019-11-07 16:08:49"
__proto__: Object
vendor: null

I want to do something if validation_status in first place exists and if its key called name is a certain value for example "pending". How can I do that in blade?

Here is my try, where right now the else condition gets executed as true, so something is wrong with my if condition:

    <p>
    @if($item->validation_status && $item->validation_status !== null) 
    @if($item->validation_status->name  === "pending" )
     <?php echo link_to('admin/items/' . $item->id . '/validation-status' . $item->validation_status->id . '/complete', 'Validate', array('class' => 'btn btn-primary w-full')); ?>
     <?php echo link_to('admin/items/' . $item->id . '/validation-status' . $item->validation_status->id . '/documentation-needed', 'Request documentation', array('class' => 'btn btn-primary w-full')); ?>
     <?php echo link_to('admin/items/' . $item->id . '/validation-status' . $item->validation_status->id . '/reject', 'Reject', array('class' => 'btn btn-primary w-full')); ?>
    @endif
    @else
      <?php echo Form::submit('Accept and Save!', array('class' => 'btn btn-primary w-full')); ?>
    @endif
    </p>

Upvotes: 2

Views: 4885

Answers (2)

Martin Tonev
Martin Tonev

Reputation: 775

Way more clear way is to use Laravel build-in helper 'optional'

For example, this code will not throw an error if the relation is null

  {{ optional($this->category)->name }}

Upvotes: 0

Piyush
Piyush

Reputation: 72

It's an object, not an array.

@php $check = isset($items->validation_status); @endphp

isset() will return false if the property doesn't exist or if it is null.

So it's perfect for your situation.

@if($check)
    //Execute your code
@endif

Upvotes: 1

Related Questions