Attempt to read property "color_name" on bool

Advertisements

I want to display the first color of the product.

Product.php

public function colors()
{
    return $this->belongsToMany(Color::class);
}

blade

@if($product->colors->count() > 0)
    @foreach($product->colors->first() as $color)
        <div data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="{{ $color->color_name }}">
            <input type="radio" id="color-{{ $color->id }}" name="color" value="color-{{ $color->id }}">
            <label for="color-{{ $color->id }}">
                <span>
                    <img src="{{ asset('themes/images/check.svg') }}" alt="{{ $color->color_name }}">
                </span>
            </label>
        </div>
    @endforeach
@endif

>Solution :

$product->colors->first() is an instance of Color model. So $color in @foreach loop is a property of Color model. If you want to display first color, do the below:

@if($product->colors->count() > 0)
    @php $color = $product->colors->first(); @endphp
    <div data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="{{ $color->color_name }}">
        <input type="radio" id="color-{{ $color->id }}" name="color" value="color-{{ $color->id }}">
        <label for="color-{{ $color->id }}">
            <span>
                <img src="{{ asset('themes/images/check.svg') }}" alt="{{ $color->color_name }}">
            </span>
        </label>
    </div>
@endif

Leave a ReplyCancel reply