You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Laravel中HasAttributes.php的ErrorException异常

Solution to Laravel Appended Attribute JSON Encoding Error

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 $appends array correctly tells Laravel which custom attributes to include when converting models to JSON, eliminating the count() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:23:57