如何修复Laravel中HasAttributes.php的ErrorException异常
Let's walk through fixing the error you're encountering step by step:
1. Fix the $appends Property (Root Cause of the Count Error)
The first issue is that your $appends property is defined as a string, but Laravel requires it to be an array of attribute names. When Laravel tries to process the appended attributes, it attempts to count the value of $appends—and since a string isn't countable, that's exactly what triggers the error you're seeing.
Corrected Code:
// In App\User_Tax.php protected $appends = ['percentage']; // Changed from a single string to an array
2. Add a Null Check for the Dependency Query
In your getPercentageAttribute method, you don't verify if the query to user_taxes_dependencies returns a result. If no matching record exists, trying to access $d->percentage will throw another error. Let's add a safety check here:
Updated Attribute Method:
public function getPercentageAttribute() { $p = SystemParameterSP::where('serviceprovider_id', $this->user_type_id)->first(); if ($p) { return $p->value1; } $d = DB::table('user_taxes_dependencies') ->where('system_tax_id', $this->system_tax_id) ->first(); // Return the percentage only if $d exists, otherwise a default value return $d?->percentage ?? 0; // Using null-safe operator and null coalescing for brevity }
(Note: The ?-> null-safe operator works in PHP 8.0+. If you're on an older version, you can use return $d ? $d->percentage : 0; instead.)
3. Confirm JSON Encoding Works
Once you've made the above fixes, your blade code should serialize the model collection to JSON without issues:
var user_taxes = {!! json_encode($user_taxes) !!};
Why These Fixes Resolve the Problem:
- The
$appendsarray correctly tells Laravel which custom attributes to include when converting models to JSON, eliminating thecount()error. - The null check ensures your attribute method doesn't fail unexpectedly if no dependency record is found, making your code more robust.
Content of the question comes from Stack Exchange, asked by Suganthan Sivananthan

