根据数据库foo_options字段值返回对应SVG的问题求助
Let's break down the two key issues causing your code to always return the green SVG, even when foo_options is 3:
1. The Accessor Isn't Checking the Actual foo_options Value
Your getOptionValueAttribute method is checking literal strings like '1' instead of the actual value of the foo_options field. In PHP, any non-empty string evaluates to true, so the first if ('1') condition will always pass—no matter what the real foo_options value is.
Fixed Model Accessor Code
public function getOptionValueAttribute(){ // Grab the actual value of your foo_options field from the model $optionValue = $this->foo_options; if ($optionValue === '1') { return '<svg>Green</svg>'; } elseif ($optionValue === '2') { return '<svg>Orange</svg>'; } elseif ($optionValue === '3') { return '<svg>Red</svg>'; } else { return ''; } }
We use $this->foo_options to reference the model's actual field value, and strict comparison (===) ensures we match both value and type to avoid unexpected matches.
2. Business Logic Uses Assignment Instead of Comparison
In your conditional check, you're using the assignment operator (=) instead of a comparison operator (== or ===). This means you're setting some_options to '1' every time the code runs, then evaluating that assignment result (which is always '1', a truthy value).
Fixed Business Logic Code
Option 1 (cleaner with in_array):
$validOptionValues = ['1', '2', '3']; if (in_array($bar->barDetail->some_options, $validOptionValues, true)) { dd($bar->barDetail->optionValue); }
The third true parameter in in_array enables strict type checking, just like ===.
Option 2 (explicit comparisons):
if($bar->barDetail->some_options === '1' || $bar->barDetail->some_options === '2' || $bar->barDetail->some_options === '3') { dd($bar->barDetail->optionValue); }
With these fixes, when foo_options is 3, your accessor will correctly return the red SVG.
内容的提问来源于stack exchange,提问作者daugaard47

