在我的所有观看中,我已经能够访问{{Auth :: user() – > name}}默认情况下,我正在尝试添加访问{{Profile :: user() – > ..的功能. .}在我的观点中,但我遇到了一些麻烦.我真的不想使用视图作曲家,如果我不需要作为this post suggests因为看起来我需要手动列出每个视图.相反,我选择使用文档中列出的AppServiceProvider boot method.问题是我仍然无法调用{{Profile :: user() – > title}}.我收到以下错误:
ErrorException in AppServiceProvider.php line 19:
Non-static method App\Profile::user() should not be called statically, assuming $this from incompatible context
这是我的AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use View;
use App\Profile;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
View::share('user', Profile::user());
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
这是我的模型Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
//
protected $fillable = [
'bio',
'linkedin_url',
'facebook_url',
'twitter_username',
'title',
'profile_image',
'user_id',
];
public function user()
{
return $this->belongsTo('user');
}
}
我究竟做错了什么?如何在所有视图中访问用户个人资料数据?我能看一个例子吗?
解决方法:
您根本不需要共享此变量,因为您只想获取用户的配置文件(您始终加载用户数据)并且它是一对一的关系.只需添加适当的关系:
public function profile()
{
return $this->hasOne('\App\Profile');
}
然后在应用程序的任何位置使用它:
auth()->user()->profile->city
如果您将共享变量,您将向所有视图添加第二个查询,在真实应用程序中,您绝对不希望这样做.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。