Error creating a new related record

3

I have a table related to other PRODUCTS AND MARKS, what happens is that when I create brands and products everything is going well. The problem is when I delete a brand and create another one, and when creating a new product with a role, it sends me the following error:

In my controller I have:

public function create()
{
    $marks = Mark::lists('name','id')->prepend('Seleccioname la Marca');
    return view('product.create')->with('marks',$marks);

}

And in the view:

{!! Form::select('marks_id',$marks,null,['id'=>'marks_id','class'=>'form-control']) !!}

I have these records in marks with their id:

But when I see the source code, I get a list from value 1 to n that are not correct.

    
asked by Marcial Cahuaya Tarqui 28.01.2017 в 17:03
source

1 answer

2

The problem is that you are using the prepend() method to add the value Seleccione la marca , but you are not specifying the second parameter, which is the key to that value. When you do not specify it, this method uses the PHP_unshift () function, which restarts the numerical indexes of the array / array.

Illuminate\Support\Collection

/**
 * Push an item onto the beginning of the collection.
 *
 * @param  mixed  $value
 * @param  mixed  $key
 * @return $this
 */
public function prepend($value, $key = null)
{
    $this->items = Arr::prepend($this->items, $value, $key);

    return $this;
}

Illuminate\Support\Arr

/**
 * Push an item onto the beginning of an array.
 *
 * @param  array  $array
 * @param  mixed  $value
 * @param  mixed  $key
 * @return array
 */
public static function prepend($array, $value, $key = null)
{
    if (is_null($key)) {
        array_unshift($array, $value);
    } else {
        $array = [$key => $value] + $array;
    }

    return $array;
}

After seeing the reference of the methods in question, the solution would be:

$marks = Mark::lists('name','id')->prepend('Seleccioname la Marca', 0);

Another quick solution to not adding anything to the array would be to simply use the attribute placeholder of the html tag of the select and put the string Seleccione la marca there.

    
answered by 28.01.2017 / 17:39
source