Laravel中“尝试在布尔值上读取color_name属性”问题排查
问题分析与解决方案
错误原因
你在Blade模板中错误地对单个Color模型实例执行了遍历操作:
$product->colors->first()返回的是单个Color模型对象,而非集合。当用@foreach遍历这个对象时,会循环它的属性值(比如字符串、数字),此时循环变量$color不再是Color模型实例,而是属性的原始值(可能是布尔值、字符串等),因此尝试读取$color->color_name会抛出“尝试在布尔值上读取属性‘color_name’”的错误。
修正代码
方案1:直接获取第一个颜色(无需遍历)
@if($product->colors->count() > 0) @php $firstColor = $product->colors->first(); @endphp <div data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="{{ $firstColor->color_name }}"> <input type="radio" id="color-{{ $firstColor->id }}" name="color" value="color-{{ $firstColor->id }}"> <label for="color-{{ $firstColor->id }}"> <span> <img src="{{ asset('themes/images/check.svg') }}" alt="{{ $firstColor->color_name }}"> </span> </label> </div> @endif
方案2:更简洁的空值判断写法
@if($firstColor = $product->colors->first()) <div data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="{{ $firstColor->color_name }}"> <input type="radio" id="color-{{ $firstColor->id }}" name="color" value="color-{{ $firstColor->id }}"> <label for="color-{{ $firstColor->id }}"> <span> <img src="{{ asset('themes/images/check.svg') }}" alt="{{ $firstColor->color_name }}"> </span> </label> </div> @endif
方案3:在模型中封装方法(复用性更强)
在Product.php中添加方法:
public function firstColor() { return $this->colors()->first(); }
然后在Blade模板中调用:
@if($firstColor = $product->firstColor) <div data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="{{ $firstColor->color_name }}"> <input type="radio" id="color-{{ $firstColor->id }}" name="color" value="color-{{ $firstColor->id }}"> <label for="color-{{ $firstColor->id }}"> <span> <img src="{{ asset('themes/images/check.svg') }}" alt="{{ $firstColor->color_name }}"> </span> </label> </div> @endif
内容的提问来源于stack exchange,提问作者Mahmoud Khoravi
相关产品推荐
相关产品推荐

