1

Given a form in the format:

<form method="POST" action="{{ route('post') }}">
{{ csrf_field() }}
@foreach([
    'firstname' => 'First name',
    'lastname' => 'Last name',
] as $key => $label)
    <label for="person[{{ $key }}]">{{ $label }}</label>
    <input name="person[{{ $key }}]" id="person[{{ $key }}]" type="text" />
@endforeach
<input type="submit" value="Send" />
</form>

And a model:

use Illuminate\Database\Eloquent\Model;

class Person extends Model
{
    protected $fillable = [
        'firstname',
        'lastname',
    ];
}

I would like to use Laravel's Illuminate\Http\Request::input() function to retrieve all the person fields from the form and fill the model from it.

The example route that I used to test this functionality is:

use Illuminate\Http\Request;
use App\Person;

Route::post('/testcase', function(Request $request) {
    $person = new Person;
    $fields = $request->input('person.*');
    $person->fill($fields);
    var_dump(
        $person->firstname,
        $person->lastname,
        $fields
    );
    return response('');
})->name('post');

However, this returns the following response:

NULL
NULL
array(2) {
[0]=>
string(4) "John"
[1]=>
string(3) "Doe"
}

(Where the form was filled with the values, "firstname" => "John" and "lastname" => "Doe")

Is it possible to retrieve the array inputs from this form with their corresponding keys ("firstname" and "lastname") instead of numerical keys, or will I have to specify all the keys manually?

1
  • try adding value="{{ $label }}" in the blade view Commented Jun 26, 2018 at 18:26

1 Answer 1

1

Change the way you access the input to

$fields = $request->input("person");

You should get

array:2 [▼
  "firstname" => "John"
  "lastname" => "Doe"
]

You should have no issue filling those fields with that logic. If you're trying to create multiple people in a single post, you'd need to use an extra index on your form:

<form method="POST" action="">
  {{ csrf_field() }}
  @foreach(['firstname' => 'First Name', 'lastname' => 'Last Name'] as $key => $label)
  <label for="person[0][{{ $key }}]">{{ $label }}</label>
  <input name="person[0][{{ $key }}]" id="person[0][{{ $key }}]" type="text" />
  @endforeach
  <input type="submit" value="Send" />
</form>

And on the backend, in a loop, access as:

for($request->input("person") AS $index => $fields){
  $person = new Person;
  $person->fill($fields);
}

// OR

$fields = $request->input("person.0");
$person = new Person;
$person->fill($fields);

You'd need a way to maintain indices on the frontend when dynamically creating fields, but that's a different issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.