Alimur Razi Rana
Alimur Razi Rana

Reputation: 87

how to Pass array from view to controller in Laravel?

I make a form in blade.php, Here I can select multiple checkbox, and I want to pass selected input’s value to controller in a array.But I failed, I can not send the data. Here is code from view. The selected input’s value can be 1,2 etc;

<form method="post" action="{{action('votesubmitController@votesubmit')}}" class="form">

<input type="hidden"  name="_token" value="{{ csrf_token() }}">

@foreach($candidate_list[$post_list->id] as $candidate_list[$post_list->id])

<li>
  <input type="checkbox"  name= "selected[]"  value= {{ 
$candidate_list[$post_list->id]->id }}>
  <label>
  <!-- some code here -->
  </label>
</li>

@endforeach
<button type="submit" id="login-button">Submit</button>
</form>

Here is route-

Route::post('/votesubmit','votesubmitController@votesubmit');

If I write return $input in controller I find –

{"_token":"TQIUxVz0LjzM84Z7TaUPk3Y7BLZPjmXUyhXhlQfp","selected":
  ["1","2"]}

That’s I need. I do not know how to get selected value. When I get specific route error exception happens . and says "Undefined variable: selected". Here is my Controller’s code-

class votesubmitController extends Controller
{
public function votesubmit()
{
  $input = Input::all();
 // return $input;     
  foreach ($selected as $selected) {
     echo $selected;
  }
}
}

Upvotes: 1

Views: 11532

Answers (2)

Nirbhay Kularia
Nirbhay Kularia

Reputation: 101

Either use $selected = $input['selected'] Or pass it using Ajax.

Upvotes: 0

PRADEEP PANDEY
PRADEEP PANDEY

Reputation: 344

// You can try this
class votesubmitController extends Controller
{
 public function votesubmit()
 {
  //$input = Input::all();
  //$selected = $input['selected'];
  $selected = Input::get('selected');   
   foreach ($selected as $selected) 
   {
    echo $selected;
   }
 }
}

Upvotes: 2

Related Questions