laravel: 无法在控制器中使用模型方法获取属性

laravel: unable to use model methods in controller to get attribute

我已经尝试这样做一段时间了。大多数时候,我通过使用访问器来解决它。我目前正在尝试获取该列是否存在,并且我在我的模型中创建了一个函数,该函数假设为 return 布尔值。

型号代码:

class Inventory extends Model
{
    protected $attributes = ['inventory'];   
    protected $appends = ['colorThumb'];

    public function hasAttribute($attr){
      return array_key_exists($attr, $this->attributes);
    }
}

控制器代码:

public function allInvOperation(Request $request){
    $inv = Inventory::where('is_deleted', 0)->with(['product', 'size','color'])->orderByDesc('id')->get();       
    if(!is_null($request->searchText)){
        dd($inv->hasAttribute('inventory'));

        $inv = Inventory::where('is_deleted', 0)->with(['product', 'size','color'])->orderByDesc('id');

        if($request->inv_filter == 'inventory'){
            $inv = $inv->where('inventory', 'like', "%".$request->searchText."%")->get();
        }
        if($request->inv_filter == 'code'){
            $inv = $inv->whereHas('product', function ($q) use ($request){
                $q->where('code', "%".$request->searchText."%");
            })->get();
        }
    }

错误

Method Illuminate\Database\Eloquent\Collection::hasAttribute does not exist.

您在 hasAttribute 上执行的代码是一个 Collection 对象,您需要对该查询使用 first 以获得一个结果,稍后您可以在该结果上执行 hasAttribute