在 Laravel 模型中创建自定义变量/属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37216229/
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
Creating custom variables/attributes in Laravel Model
提问by Stetzon
I am trying to create a custom attribute inside of a Laravel Model. This attribute would be the same for all of the Model instances (static?). The goal is to use this attribute to populate a select dropdown when creating a Model instance. Example:
我正在尝试在 Laravel 模型中创建自定义属性。该属性对于所有模型实例(静态?)都是相同的。目标是在创建模型实例时使用此属性填充选择下拉列表。例子:
class User extends Model
{
protected $table = 'users';
protected $guarded = [ 'id' ];
public $timestamps = true;
protected $genders = ['male'=>'Male', 'female'=>'Female']; //custom
public static function getGenderOptions() {
return $genders;
}
}
Then when building out the form, I could do something like:
然后在构建表单时,我可以执行以下操作:
// UserController.php
$data['select_options'] = User::getGenderOptions();
return view('user.create', $data);
// create.blade.php
{!! Form::select( 'gender', $select_options ) !!}
This causes me to get the error:
这导致我收到错误:
Undefined variable: genders
I am trying to prevent cluttering my Controller with all of the select options, as there are also a few others I haven't included.
我试图防止我的控制器被所有选择选项弄乱,因为还有一些我没有包括在内。
Thanks.
谢谢。
回答by Giedrius Kir?ys
Modify Your protected $genders
element and make it public+static. So then You can access it directly like so: User::$genders
.
修改您的protected $genders
元素并使其成为公共+静态。这样的话,您可以直接访问它,如下所示:User::$genders
。
But...my personal decision would be to move constants to config file or some kind of helper.
但是...我个人的决定是将常量移动到配置文件或某种帮助程序。
回答by Alex Anry
I guess it should be
我想应该是
public function getGenderOptions() {
return $this->genders;
}
Or simply declare $genders
as a static variable and use return self::$genders
或者简单地声明$genders
为静态变量并使用return self::$genders
Check the docs - Variable scopeand Static Keyword