Search code examples
phpsqllaravelmutators

Implode separate date of birth values from php form


Ok i'm out of ideas and have reached the end point in my research.

have a registration form with a birthdate select fields example below:

<div class="row">
    <div class="col-xs-2">
        {!! Form::selectMonth('dob_month', 1, ['class'=> 'form-control']) !!}
    </div>
    <div class="col-xs-2">
        {!! Form::selectRange('dob_date', 1, 31, 1, ['class'=> 'form-control']) !!}
    </div>
    <div class="col-xs-2">
        {!! Form::selectYear('dob_year', 1930, 1997, 1991, ['class'=> 'form-control']) !!}
    </div>
</div>

of course its in laravel's blade template.

As you can see its 3 separate select forms with dob_month, dob_date and dob_year and the values now onto the mutator thats in the user model

private function setDobAttribute($dob){

            $dobString = ['dob_year', 'dob_month', 'dob_date'];

            $this->attributes['dob'] = implode('-', array_values($dobString)); 

        }

with dob as the sql column name.

The Issue

I want to capture dob_year, dob_month, dob_date which would be structured as 1997-12-01 with using implode('-'array_values($dobString)) which would then be saved to the database.

When I go through the process of signing up a new user I get an error message of Undefined index: dob.

Now I am also getting the feeling that in the mutator function setDobAttribute($dob) I am missing something within that function code but can't seem to put my finger on what it is.

Input? suggestions?

Thank you in advance.


Solution

  • Use array_map may be...

    private function setDobAttribute($dob){
      $keys = ['dob_year', 'dob_month', 'dob_date'];
      $this->attributes['dob'] = 
        implode('-', array_map(function($key) use($dob){
          return $dob[$key];
        }, $keys)); 
      return $this;
    }