Shota
Shota

Reputation: 7330

Laravel - get all checkbox values from the Request

I have checkboxes in the HTML like this:

<input type="checkbox" name="models" value="ipad">
<input type="checkbox" name="models" value="ipod">

I am getting the whole form values in Request object, it contains a checkbox values like this:

&models=ipad&models=ipod

I am trying to extract all these values in array, like this:

["ipad", "ipod"]

I've tried but did not work:

$request->input('models')
$request->input('models.*')
$request->all()

Also did not work:

<input type="checkbox" name="models[]" value="ipad">

Upvotes: 0

Views: 3162

Answers (4)

Akash Kumar Verma
Akash Kumar Verma

Reputation: 3318

suppose if you are using like this

<form method="get" action="{{ url('/testing') }}">
  @csrf
  <input type="checkbox" name="models[]" value="ipad">
  <input type="checkbox" name="models[]" value="ipod">
   <input type="submit" name="submit">
 </form>
Then in response you get

Array
(
    [_token] => XhkdiOqbv24qhT4TnkT1liLm3GAyvTTt78vaDbBO
    [models] => Array
        (
            [0] => ipad
            [1] => ipod
        )

    [submit] => Submit Query
)


so finally you get array by $request->models

on print_r($request->models) you will get

Array
(
    [0] => ipad
    [1] => ipod
)

Upvotes: 0

Muhammad Rizwan
Muhammad Rizwan

Reputation: 488

Try

<input type="checkbox" name="models[]" value="ipad">
<input type="checkbox" name="models[]" value="ipod">

and in your controller:

  $request->models

Upvotes: 0

Iftikhar uddin
Iftikhar uddin

Reputation: 3182

Try the below code:

<input type="checkbox" name="models[]" value="ipad">
<input type="checkbox" name="models[]" value="othervalue">

If you have added models[] as array, then you can loop through the selected values like:

foreach($request->input('models') as $value){
  // $value
}

Upvotes: 0

Zoli
Zoli

Reputation: 1081

This should work:

<input type="checkbox" name="models[]" value="ipad">
<input type="checkbox" name="models[]" value="ipod">

Upvotes: 1

Related Questions