Reputation: 840
I have multiple checkboxes in the following code:
@foreach($camera_video as $video)
<input type="checkbox" name="camera_video" value="{{$video->id}}"> <label>{{$video->name}}</label>
@endforeach
I would like to see which checkboxes have been checked by the user. I just need the id (value) to store. What is the best way to do this in Laravel?
Upvotes: 13
Views: 86374
Reputation: 313
you can use has to function on the request object to check the value of the checkbox is exist and is not in the request like below;
public function store(Request $request){
if($request->has('terms')){
//Checkbox checked
}else{
//Checkbox not checked
}
}
for multiple;
public function store(Request $request){
if(in_array('Mango', $request->get('fruits'))){
//User like Mango
}else{
//User does not like Mango
}
}
$request->get('fruits') // this will return the array;
Upvotes: 2
Reputation: 93
For the multiple checkboxes in a view, you can do it like this.
@foreach($camera_video as $video)
<input type="checkbox" name="camera_videos[]" value="{{$video->id}}">
<label>{{$video->name}}</label>
@endforeach
Inside your controller, you can do it like @Buglinjo's answer or else simply use a foreach loop
. You will get the value of checked checkboxes only
$camera_videos = $request->input('camera_videos');
foreach ($camera_videos as $camera_video) {
//you can do whatever you want. I am saving it in MySqli DB
$table = new Model;
$table->video_id = $camera_video;
$table->save();
}
Upvotes: 1
Reputation: 2076
You should update name of your checkbox input to camera_video[]
as array and you are good to go. You will get input array.
<input type="checkbox" name="camera_video[]" value="{{$video->id}}"> <label>{{$video->name}}</label>
If you are using Laravel 5.x.x you should use Request object:
public function yourMethod(Request $request)
{
$cameraVideo = $request->input('camera_video');
...
}
Upvotes: 32
Reputation: 4750
You just need to define the name as an array so that you can fetch the input as array in Laravel. Like this:
<input type="checkbox" name="camera_video[]" value="{{$video->id}}"> <label>{{$video->name}}</label>
Upvotes: 1