Cannot output Laravel hasOne values in blade

27 views Asked by At

In my model I have this

public function orderTotal():HasOne {
    return $this->HasOne(OrdersTotals::class)->where('class', 'ot_total');
}

If I output with the following

{{ $order->orderTotal }}

I get a string resembling JSON.

{"id":3,"order_id":2,"title":"Total","value":5980,"class":"ot_total","sort_order":300,"created_at":"2024-03-21T11:59:23.000000Z","updated_at":"2024-03-21T11:59:23.000000Z"}

It contains all of the data I need. But I only want to display the index/key named "value"

So when I output with the following:

{{ $order->orderTotal->value }}

I get:

Attempt to read property "value" on null

When I output with the following:

{{ $order->orderTotal['value'] }}

I get

Trying to access array offset on value of type null

I've tried to reference the first index of the array with

{{ $order->orderTotal[0]->value }}

But I get

Undefined array key 0

If I try to output in a loop as follows:

@foreach ($order->orderTotal as $total)
    {{ $total }}
@endforeach

I get:

foreach() argument must be of type array|object, null given

How am I supposed to properly reference that index/key to get its value??

If I change the relationship to hasMany

public function orderTotal():HasMany {
    return $this->HasMany(OrdersTotals::class)->where('class', 'ot_total');
}

And I loop through with

@foreach ($order->orderTotal as $total)
    {{ $total['value'] }}
@endforeach

I get the value but I don't understand why I have to use HasMany and loop through when the data is there with hasOne I just can't reference it.

1

There are 1 answers

0
Sitethief On

If you do {{ $order->orderTotal?->value }} you will probably find out that some orders do not have an orderTotal, and thus also not at value for orderTotal.