简体   繁体   English

Auth :: user()有关系吗?

[英]Auth::user() with a relationship?

I have a regular users table, but I also have a user_settings table with the following relationship in my UserSettings.php file: 我有一个普通users表,但我的UserSettings.php文件中也有一个具有以下关系的user_settings表:

public function user()
{
    return $this->belongsTo('App\Models\User');
}

And a settings method within my User.php file: 还有我的User.php文件中的设置方法:

public function settings()
{
    return $this->hasOne('App\Models\UserSettings');
}

I want to be able to access the user and their settings by doing Auth::user() , but doing Auth::user()->settings->column_name gives me an error: 我希望能够通过执行Auth::user()访问用户及其设置,但是执行Auth::user()->settings->column_name给我一个错误:

Trying to get property of non-object 试图获取非对象的属性

How can I get the user's settings using Auth::user() ? 如何使用Auth::user()获得用户的设置?

You can access it like so: 您可以这样访问它:

var_dump(Auth::user()->settings);

You cannot access it like so Auth::user()->settings->column_name because you have to foreach it. 您不能像Auth::user()->settings->column_name这样访问它,因为您必须对其进行foreach。

foreach(Auth::user()->settings as $setting) {
     var_dump($setting->column_name);
}

You must set up a settings method within User model: 您必须在用户模型中设置一种设置方法:

public function settings()
{
    return $this->hasOne('App\Models\Settings');
}

You must be getting 你一定在

Trying to get property of non-object 试图获取非对象的属性

error as there may be no entry in user_settings table for the particular user. 错误,因为在user_settings表中可能没有特定用户的条目。

Your relationships look correct. 您的人际关系看起来正确。

Just go to tinker and find the user for whom you are getting the error. 只需去tinker然后find您要获取错误的用户。 Then try accessing the settings for that user. 然后尝试访问该用户的settings

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM