英文:
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');
}
}
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论