我想在Laravel模型中将环境变量作为虚拟属性获取。

huangapple go评论46阅读模式
英文:

I want to get env variable as fake attribute in laravel model

问题

我试图获取环境变量,从.env文件中获取APP_URL,但始终返回null,但当使用随机字符串时,它显示。

英文:

i was try to get environment variabel, to get APP_URL from .env,
but always return null, but when use random string it show,

class Attachment extends Model
{
    
    public function getUrlAttribute()
    {
        return env('APP_URL');
    }

}

https://i.stack.imgur.com/7YkB5.png

答案1

得分: 2

根据Laravel官方文档这里

> 你可以在应用程序的任何地方使用全局config函数轻松访问配置值。可以使用“点”语法访问配置值,其中包括文件名和要访问的选项名称。还可以指定默认值,如果配置选项不存在,将返回该值。

在你的情况下:

$value = config('app.url');

// 如果配置值不存在,可以检索默认值...
$value = config('app.url', 'somesdefaulturl');

你的代码应该如下:

class Attachment extends Model
{
    
    public function getUrlAttribute()
    {
        return config('app.url');
    }

}
英文:

Per Laravel official documentation here

> You may easily access your configuration values using the global
> config function from anywhere in your application. The configuration
> values may be accessed using "dot" syntax, which includes the name of
> the file and option you wish to access. A default value may also be
> specified and will be returned if the configuration option does not
> exist

In your case:

$value = config('app.url');

// Retrieve a default value if the configuration value does not exist...
$value = config('app.url', 'somedefaulturl');

Your code should look as:

class Attachment extends Model
{
    
    public function getUrlAttribute()
    {
        return config('app.url');
    }

}

答案2

得分: 0

为什么你需要从模型获取它,当你可以在你的代码中的任何地方随时随地获取它?

$url = config('app.url');

对你来说已经足够了。祝你成功。

英文:

Why do you need to get it from the model when you can just get it from everywhere and anywhere in your code?

$url = config('app.url');

is enough for you. Best of success

huangapple
  • 本文由 发表于 2023年5月28日 01:42:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76348245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定