Laravel模型添加自定义is_qualified属性返回值异常问题求助
is_qualified Accessor in Your Laravel User Model Hey there, let's figure out why your is_qualified accessor isn't working as expected—here's the breakdown and fix:
The Root Issue
Your current accessor code has a critical misstep in how it uses the qualified scope:
public function getIsQualifiedAttribute($value) { return $this->qualified()->first() ? true : false; }
When you call $this->qualified(), you're launching a new query that checks all users in your table for years_of_experience >=5. The first() here returns the first matching user from the entire database—not whether the current user meets the condition. That's why you're getting incorrect results every time.
Solution 1: Directly Check the Current User's Attribute
The simplest and most efficient fix is to skip the scope entirely in the accessor, and just evaluate the current model's own years_of_experience value:
public function getIsQualifiedAttribute() { // We don't need the $value parameter since this is a computed attribute return $this->years_of_experience >= 5; }
This directly checks the user's experience level, so it'll always return the correct boolean value for the user you're working with.
Solution 2: Reuse the Scope for the Current User (If Needed)
If you want to keep reusing the qualified scope logic (in case you add more conditions later), adjust the accessor to target only the current user:
public function getIsQualifiedAttribute() { return $this->qualified()->whereKey($this->getKey())->exists(); } public function scopeQualified($query) { return $query->where("years_of_experience",">=",5); }
Here, whereKey($this->getKey()) restricts the scope query to the current user, and exists() returns a clean boolean indicating if they match the scope's conditions.
Testing in Blade
Keep using your original Blade syntax—it'll now work correctly:
{{ $user->is_qualified }}
If you want explicit "true"/"false" instead of Blade's default 1/empty output, you can cast it:
{{ $user->is_qualified ? 'true' : 'false' }}
内容的提问来源于stack exchange,提问作者Peril

