4

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:

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.

2 Answers 2

6

Modify Your protected $genders element and make it public+static. So then You can access it directly like so: User::$genders.

But...my personal decision would be to move constants to config file or some kind of helper.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this worked. Right now these options are only being used for the Users, but if they start being used elsewhere, then I would plan to move them to some sort of config.
0

I guess it should be

public function getGenderOptions() {
    return $this->genders;
}

Or simply declare $genders as a static variable and use return self::$genders

Check the docs - Variable scope and Static Keyword

3 Comments

Also Visibility and Scope resolution docs might be helpful: docs.php.net/language.oop5.visibility docs.php.net/language.oop5.paamayim-nekudotayim
don't think $this->genders would work inside the model, as it has to be in the object instance, correct? But I did end up using self::$genders, after declaring $genders as public static, as suggested by @Giedrius Kiršys
Well, with $this->genders it can be used as $data['select_options'] = (new User())->getGenderOptions(); but if you want to use it statically, then yes, you should declare $genders as static. Btw, if you are going to extend your class User and change $genders value in a new class, then you should use static instead of self: return static::$gender

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.