Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Laravel - HTML Forms array of values

Tags:

html

php

laravel

I have the following form, with fields:

  • From
  • To
  • Price

You can add multiple rows and this data is then sent to the controller.

What I want is:

Let's assume there are two rows of inputs currently on the page, the output would therefore be something like:

$rates => array(2)
   0 => [ 
      "from" => 1, 
      "to"   => 2,
      "price" => 10
   ], 
   1 => [ 
      "from" => 1, 
      "to"   => 2,
      "price" => 10
   ]   

I have tried to do the following (HMTL):

  <input type="text" name="rates[]" placeholder="Enter rate from" 
  autocomplete="off" class="form-control">

But this just gives me an array of 6 with all the values, with no way of knowing the order. I have also tried the following:

<input type="text" name="rates[]['from']" placeholder="Enter rate from" 
      autocomplete="off" class="form-control">

 <input type="text" name="rates[]['to']" placeholder="Enter rate to" 
      autocomplete="off" class="form-control">

 <input type="text" name="rates[]['price']" placeholder="Enter rate price" 
      autocomplete="off" class="form-control">

This isn't producing the result(s) that I need. Is it possible to do what I want to do using HTML and PHP?

like image 969
Phorce Avatar asked Mar 08 '23 21:03

Phorce


1 Answers

Instead of using an index-based approach, you can use three different arrays (from, to and prices e.g.). You can then iterate through all of them to get your values.

HTML

<input type="text" name="from[]" placeholder="Enter rate from" 
      autocomplete="off" class="form-control">

 <input type="text" name="to[]" placeholder="Enter rate to" 
      autocomplete="off" class="form-control">

 <input type="text" name="prices[]" placeholder="Enter rate price" 
      autocomplete="off" class="form-control">

PHP

 $from = [
        'Jane',
        'Bob',
        'Mary',
    ];
    $to = [
        'John',
        'Alex',
        'Paul',
    ];
    $prices = [
        10,
        2500,
        2,
    ];

  $finalValues = [];
  foreach ($prices as $i => $price) {
    $finalValues[
              "from" => $from[i];
              "to" => $to[i];
              "price" => $price;
  } 

This only works when your values are all required or give back null when not set

like image 113
manniL Avatar answered Mar 17 '23 21:03

manniL