HasRelationships.php中的ErrorException

时间:2017-05-12 17:26:51

标签: php laravel eloquent relationship

我得到了这个错误,但我不确定是因为关系还是其他什么?

错误

ErrorException in HasRelationships.php line 487:
Class 'Company' not found 

user.php的

public function company(){ $this->belongsTo('Company', 'user_id'); }

Company.php

public function user(){ $this->belongsTo('User') ; }

现在我的目标是隐藏导航栏中的“创建列表”按钮,如果用户与公司表没有关系。我知道我可以使用角色或中间件来制作它,但是我的朋友给我这样的东西并且告诉我这样做更容易。

if(count($user->company) > 0) 

所以现在我想弄清楚如何,但仍然无法弄清楚如何修复错误。

导航视图

@inject('user', 'App\User')
   @if(count($user->company) > 0)
     <li><a href="{{route('listings.create', [$area])}}">Add listing</a></li>
   @endif

/// UPDATE

它没有找到类'Company',因为我没有在我的关系中使用完整的命名空间,但现在我收到了这个新的错误。

错误

ErrorException in HasAttributes.php line 403:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation 

(View: /Users/username/Desktop/laravel/resources/views/layouts/partials/_navigation.blade.php) 
(View: /Users/username/Desktop/laravel/resources/views/layouts/partials/_navigation.blade.php) 
(View: /Users/username/Desktop/laravel/resources/views/layouts/partials/_navigation.blade.php)

1 个答案:

答案 0 :(得分:4)

在关系代码中使用完整命名空间:

public function company()
{
    return $this->belongsTo('App\Company', 'user_id');
}