0

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
  • Can you do this: `@if(gettype($color->color_name)=='boolean') dd($color) @endif`? Paste it right below foreach. – Sachin Bahukhandi Mar 24 '23 at 12:38
  • 1
    You need to find out why (at least one instance of) `$color` is a boolean instead of an object. Presumably it's because `$product->colors` is empty and therefore there's nothing for `first()` to return - either that or what it does return is not an object. Have you done any debugging so far? – ADyson Mar 24 '23 at 12:40
  • 1
    P.S. As a logic-related aside, `->first()` only returns one record (at most)...so why the foreach loop? https://laravel.com/docs/10.x/collections#method-first – ADyson Mar 24 '23 at 12:41
  • @SachinBahukhandi I see blank page – Mahmoud Khoravi Mar 24 '23 at 12:50
  • @ADyson How to return one record? – Mahmoud Khoravi Mar 24 '23 at 12:51
  • @MahmoudKhoravi by using first(). Therefore, there's no need to loop if you only expect one record. That was my point – ADyson Mar 24 '23 at 12:56

1 Answers1

2

$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
Khang Tran
  • 2,015
  • 3
  • 7
  • 10