user573 user573 - 5 months ago 36
MySQL Question

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');

Answer

The problem was then solved with a change in UI. I feel the problem could have been solved using the below method. Hope that helps someone.

 $input = $request->all();
    $parent = $input['animal_parent'];

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

    unset($input['animal_parent']);
    $animal = new Animal($input);
    $animal->save();`