如何在 Laravel 中为 Auth::user() 添加自定义值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45610513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add custom value to Auth::user() in Laravel
提问by Parth Vora
I've some custom value that I want to use in the whole project when the user logs in. I am writing a function in controllers but calling that static method every time can make code little bit lengthy. Instead of calling the function I want to assign a custom value to Auth::user()
so I can use it anywhere in the project. I tried it below code but it won't work
当用户登录时,我想在整个项目中使用一些自定义值。我正在控制器中编写一个函数,但每次调用该静态方法都会使代码有点冗长。我想为其分配自定义值而不是调用函数,Auth::user()
以便我可以在项目中的任何地方使用它。我在下面的代码中尝试过,但它不起作用
public static function getUserDetailById($id){
//Do Something and assign value to $custom_val
Auth::user()->custom = $custom_val;
}
But It's not working in any controller or view. I tried to check custom value in Auth::user()
but it's missing.
但它不适用于任何控制器或视图。我试图检查自定义值,Auth::user()
但它丢失了。
Is there any way to add custom value to Auth::user()
without adding new column in a table?
有什么方法可以添加自定义值Auth::user()
而不在表中添加新列?
回答by Parth Vora
It is very simple. You can create an Accessor for that.
这很简单。您可以为此创建一个访问器。
App\User.php
应用\用户.php
public function getCustomAttribute()
{
return 'Custom attribute';
}
Now, you can access it anywhere using:
现在,您可以使用以下方式在任何地方访问它:
echo Auth::user()->custom;
More info:
更多信息:
https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
回答by Zayn Ali
Add custom
to your User
model $appends
array.
添加custom
到您的User
模型$appends
数组。
protected $appends = [ 'custom' ];