vendredi 30 octobre 2015

Unable to save select box options in Laravel 5.1

I am working on my first project using Laravel 5.1. Uses a selectbox in a form.

{!!Form::select('animal_parent[]', array('1' =>  'opt1',  '2' =>  'opt2',  '3' => 'opt3', '4' => 'opt4',), null, ['id' => 'animal_parent', 'disabled' => 'disabled', 'multiple' => 'multiple', 'class' => 'form-control'])!!}

Selection limited to two options which need to saved in two columns, 'male_parent' and 'female_ parent' of the 'animal' table.

There are no 'male_parent' and 'female_ parent' element names in the form. Similarly no 'animal_parent' field in 'animal' table.

Values are set as expected in the code given below. However, the insert command does not reflect the newly set values and throws an error.

"ErrorException in helpers.php line 671: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array."

Any help would be much appreciated.

First attempt using mutators

public function setMaleParentAttribute()
    {

        $parent = Input::get('animal_parent');
        $this->attributes['male_parent'] = intval($parent[0]);
    }

    public function setFemaleParentAttribute(AddAnimalRequest $request)
    {
        $parent = Input::get('animal_parent);
        if (isset($parent[1])) {
           $this->attributes['female_parent'] = intval($parent[1]);
        } else {
            $this->attributes['female_parent'] = intval($parent[0]);
        }
     unset($request->animal_parent);

Second attempt using the store() method in the controller.

            $animal = new Animal($request->all());
            $parent = Input::get('animal_parent');

            $animal['male_parent'] = intval($parent[0]);
            if (isset($parent[1])) {
                $animal['female_parent'] = intval($parent[1]);
            } else {
                $animal['female_parent'] = intval($parent[0]);
            }

            unset($request->animal_parent);
            Auth::user()->animals()->save($animal);
            return redirect('animals');



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire