How to validate at least one checkbox is checked in a loop in Laravel? - php

I'm trying to validate my checkbox from a loop, where at least one is checked and displays an error/alert or disable the submit button instead if there is no checkbox checked. I tried putting a required method inside my checkbox, but the checkbox is in a loop that's why it requires all to be checked. That's why I tried the script code below which I found on the internet but that doesn't seem to work for me.
Below is my code in blade form
<form id="contact" action="{{url('/reservation')}}" method="post" enctype="multipart/form-data">
#csrf
<div class="row col-12">
#foreach($data as $data)
<div class="row sm-6 ml-4 mb-1" class="no-gutters" style="height:25px; width: auto;">
<p class='text-dark mr-2'><input type="checkbox" name="prod_name[]" value="{{$data->title}}" class="products product{{$data}}" onClick="checkTest()"/> {{$data->title}}</p>
<p class='text-dark'>Qty:</p><input style="width:80px; height:25px;" type="number" name="prod_qty[{{$data->title}}]" min="1" value="1" class="form-control ml-2">
<input type="hidden" name="product_fee[{{$data->title}}]" value="{{$data->price}}">
<input type="hidden" name="prod_id[{{$data->title}}]" value="{{$data->id}}">
</div>
#endforeach
</div>
<div class=" col-lg-12 mt-5">
<fieldset>
<button name="submit" type="submit" id="form-submit" class="main-button-icon">Make A Reservation</button>
</fieldset>
</div>
</div>
</form>
<script>
var minimumonechecked;
var checkboxes = $('.products').lenght;
function checkTest(xyz){
minimumonechecked = false;
for(i=0;i<checkboxes;i++){
if($('product' + i).is(':checked')){
minimumonechecked = true;
}
}
console.log(minimumonechecked)
};
</script>
This is also the code in my controller, other data such as names are also part of the form but I cut it out by focusing on the checkbox
public function reservation(Request $request)
{
if(Auth::id()){
$user_id=Auth::id();
$products = '';
$reserved_qty=0;
$product_fee=0;
$prod_id=0;
$checked_array = $request->input('prod_name', []);
$quantities = $request->input('prod_qty', []);
$fees = $request->input('product_fee', []);
$productid = $request->input('prod_id', []);
foreach($checked_array as $value){
$data = new reservation;
$data->user_id=$user_id;
$data->name=$request->name;
$data->email=$request->email;
$data->phone=$request->phone;
$data->address=$request->address;
$data->date=$request->date;
$data->time=$request->time;
$data->status="pending";
$data->productz=$request->products="{$value}";
$data->reserved_qty=$request->$reserved_qty="{$quantities[$value]}";
$data->product_fee=$request->$product_fee=$fees[$value]*$quantities[$value];
$data->prod_id=$request->$prod_id=$productid[$value];
$data->save();
}
return redirect()->back();
}else{
return redirect('/login');
}

There are a many ways to achieve your desired result, how I would approach it is as follows (note this is not exhaustive, it's a functional example).
On the client, use JavaScript to select all your product checkboxes, iterate over any found and attach event handlers to each of them which listen for the changed event (i.e. checked and unchecked). When the state of a checkbox is checked, add it to a Set so that we can track how many are selected. Based on the number of checked checkboxes, enable/disable form submission.
That theory out of the way, some code:
HTML:
<script src="https://cdn.tailwindcss.com"></script>
<div class="flex flex-col place-content-center items-center h-screen space-y-4">
<div class="flex align-items-center space-x-2">
<h1 class="underline font-bold decoration-orange-500 decoration-2">
<a href="https://stackoverflow.com/questions/73834200/how-to-validate-at-least-one-checkbox-is-checked-in-a-loop-in-laravel">
How to validate at least one checkbox is checked in a loop in Laravel?
</a>
</h1>
</div>
<div class="flex align-items-center space-x-2">
<input type="checkbox" class="products" name="products[]" id="product-a" />
<label for="product-a" class="text-sm">Product A</label>
</div>
<div class="flex align-items-center space-x-2">
<input type="checkbox" class="products" name="products[]" id="product-b" />
<label for="product-b" class="text-sm">Product B</label>
</div>
<div class="flex align-items-center space-x-2">
<input type="checkbox" class="products" name="products[]" id="product-c" />
<label for="product-c" class="text-sm">Product C</label>
</div>
<div class="flex align-items-center space-x-2">
<button class="px-4 py-2 rounded bg-orange-600 hover:bg-orange-700 text-white text-sm" id="form-submit">Submit</button>
</div>
</div>
JavaScript:
window.addEventListener('DOMContentLoaded', function () {
// get all the product checkbox elements
var productCheckboxes = document.querySelectorAll('.products');
// holder for the checked products
var checkedProducts = new Set();
// pointer to the form submit button
var formSubmitButton = document.querySelector('#form-submit');
// attach change event handlers to each of the checkboxes
productCheckboxes.forEach((checkbox) => {
checkbox.addEventListener('change', function (e) {
e.target.checked
? checkedProducts.add(e.target.id)
: checkedProducts.delete(e.target.id);
});
});
//
formSubmitButton.addEventListener('click', function (e) {
handleClientSideValidation();
});
// do some client side validation (do not rely on this alone!)
function handleClientSideValidation() {
if (checkedProducts.size == 0) {
alert('Ugh-oh, something is foobar Captain. You need to select at least 1 product.');
return;
}
alert('Validating ...');
}
})
Example CodePen
Now lets apply the above to a Laravel example using #foreach and Eloquent models. I am going to assume you already have a Product model, migration and some data seeded.
Form HTML:
<form action="{{ route('reservation') }}" method="POST" id="products-form">
<div class="flex flex-col place-content-center items-center h-screen space-y-4">
#csrf
<div class="flex align-items-center space-x-2">
<h1 class="underline font-bold decoration-orange-500 decoration-2">
<a href="https://stackoverflow.com/questions/73834200/how-to-validate-at-least-one-checkbox-is-checked-in-a-loop-in-laravel">
How to validate at least one checkbox is checked in a loop in Laravel?
</a>
</h1>
</div>
#if ($errors->any())
<div class="px-4 py-2 bg-red-500 text-white text-sm rounded-sm">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#foreach($products as $product)
<div class="flex align-items-center space-x-2">
<input type="checkbox" class="products" name="products[]" id="product-{{ $product->id }}" value="{{ $product->id }}" />
<label for="product-{{ $product->id }}" class="text-sm">{{ $product->title }}</label>
</div>
#endforeach
<div class="flex align-items-center space-x-2">
<button type="submit" class="px-4 py-2 rounded bg-orange-600 hover:bg-orange-700 text-white text-sm" id="form-submit">Submit</button>
</div>
</div>
</form>
As we all know you shouldn't rely soley upon client side validation, so you'll want to do some server side validation too. Once you've validated your request data, you can do whatever you want with it (I just get the products from the database in this example). I have put the code directly in a Route within web.php as I am lazy, you'd obviously use it in your ProductController function.
routes/web.php:
Route::post('/', function (Request $request) {
// perform some validation
// $validate will contain all the data that passed validation
$validated = $request->validate([
// products must be present in the request AND an array
'products' => ['required', 'array'],
// each of the products in the request, must have an ID present in the database
'products.*' => ['exists:products,id']
]);
// if we get here, validation was successfull
// do whatever you want with the $validated data
// I am just getting the Products as an example
$products = \App\Models\Product::whereIn('id', $validated['products'])->get();
// dump the Products
dd($products->all());
})->name('reservation');
Example PHP Sandbox
Quite a lot to taken in but hopefully that makes sense.

When you tick on checkbox, you need to count all checkboxes that have been checked before.
If at least checkbox is checked , you'll set disabled property on submit button is true and vice verse
<script>
$('.products').on('change', function() {
$('#form-submit').prop('disabled', $('.products:checked').length > 0);
});
</script>

Related

How to retain selected value of dropdown when redirecting

I'm currently trying to make dropdown of date to filter data. The filtering process itself working fine but I want to retain the selected date. Based on my reading you can use old helper to retain the data but it does not work for me. I'm still new using laravel.
Below are my code:
(view)
#props(['expense'])
<x-card>
<header class="text-center">
<h2 class="text-3xl font-bold uppercase mb-1">
Daily Report
</h2>
</header>
<div>
<h3 class="text-xl">
<div>
<form method="GET" action="/">
<label for="date">Daily expense on:</label>
<input class="border border-black rounded p-2" type="date" id="date" name="date" value="{{old('date')}}" />
<input class="bg-laravel text-white rounded py-2 px-4 hover:bg-black" type="submit" />
</form>
#unless(count($expense) == 0)
#foreach($expense as $data)
<li>{{$data->category}} ${{$data->amount}}</li>
#endforeach
#else
<p>No expenses found</p>
#endunless
</div>
</h3>
</div>
</x-card>
(controller)
public function index() {
return view('expenses.index', [
'expenses' => Expense::latest()->filter(request(['date']))->get()
]);
}
Hope my explanation is clear. Please inform me if it's not.

Check only one checkbox and uncheck others using livewire

I'm trying to check only one checkbox at a time and others uncheck, but when I want to check a new checkbox then the previous will uncheck, and so on.
my code in blade:
#foreach($addressEmployer as $address)
<div class="col-12 col-lg-3 p-2 m-2 rounded" style="border: dashed #a1a1a1;">
<label for="check{{$address->id}}"></label>
<div class="row">
<div class="col-2 mt-5">
<input wire:model="addressSelected.{{$address->id}}"
value="{{$address->id}}"
class="form-check-input" type="checkbox"
id="check{{$address->id}}">
</div>
<div class="col-10">
<p> {{$address->province->name}} - {{$address->city->name}}</p>
<p> {{$address->address}}</p>
<a wire:click="setAddress({{$address->id}})" class="float-end"
data-bs-toggle="modal"
href="#editAddressModal"
role="button">{{__('Edit')}}</a>
<a wire:click="$emit('addressId',{{$address->id}})" class=" me-3 float-end"
data-bs-toggle="modal"
href="#deleteAddressModal"
role="button">{{__('Delete')}}</a>
</div>
</div>
</div>
#endforeach
I read the addresses from the database and display them with foreach and I want to select one of the displayed addresses.
I am looking for the right solution to this issue. Thanks if you have a solution.
When you have multiple options but want to limit selection to a single option, radio buttons are your friend.
If the previously selected radio button is not de-selecting, it suggests you haven't grouped your radio button elements correctly using the name attribute.
Here is a simplified example to get you on the right path.
Component
class AddressComponent extends Component
{
public $addresses = Address::all();
public $selectedAddressId;
public function mount()
{
$this->addresses = Address::all();
$this->selectedAddressId = 1;
}
public function render()
{
return view('livewire.address-component-view');
}
}
Component view
<div>
#foreach ($addresses as $address)
<div class="mt-1">
<input type="radio" id="{{ $address->id }}" name="address" value="{{ $address->id }}" wire:model="selectedAddressId" />
<label for="{{ $address->id }}">{{ $address->address }}</label>
</div>
#endforeach
<h3>Selected Address ID: {{ $selectedAddressId }}</h3>
</div>
I'm not shure why you're trying this with checkbox, instead of radiobutton. But maybe you can handle something like this
public $addressSelected = [];
protected $rules = [
'addressSelected.id' => 'nullable'
];
public function updatingAddressSelected($value)
{
$this->addressSelected = [];
}
// in blade add the wire:key directive to checkbox's root div
<div class="col-2 mt-5" wire:key="checkbox-id-{{ $address->id }}">
<input wire:model="addressSelected.{{$address->id}}"
value="{{$address->id}}"
class="form-check-input" type="checkbox"
id="check{{$address->id}}"
#if(in_array($address->id,$addressSelected)) checked #endif
>
</div>

Submitting data in a Livewire child view using its <form> in the parent view

I have a parent view edit.blade.php which has a form. The form has a #livewire() for edit-step.blade.php, the child component.
edit-step.blade.php has a foreach loop that renders the input fields. At one point, foreach will loop three input fields. The submit button is in the parent view edit.blade.php. On submitting, data from the last input field is the only one being submitted. How do I make data from all the input fields be submitted ?
edit.blade.php file:
<form method="post" action="{{route('todo.update', $todo->id)}}" class="py-5">
#csrf
#method('patch')
<div class="py-1"><input type="text" name="title" value="{{$todo->title}}" class="py-2 px-2 border rounded" placeholder="Title" /></div>
<div class="py-1">
<textarea name="description" class="p-2 rounded border" placeholder="Description">{{$todo->description}}</textarea>
</div>
<div class="py-2">
#livewire('edit-step', ['steps' => $todo->steps])
</div>
<div class="py-1"><input type="submit" value="Update" class="p-2 border rounded" /></div>
</form>
edit-step.blade.php file:
#foreach($steps as $step)
<div class="flex justify-center py-2" wire:key="{{$loop->index}}" >
<input type="text" name="step_" class="py-1 px-2 border rounded" placeholder="{{ 'Describe Step '.($loop->index + 1) }}" #if ( is_object($step) ) value="{{ $step->name }}" #endif />
<span class="fas fa-times text-red-400 p-2" wire:click="remove({{$loop->index}})"/>
</div>
#endforeach
Here is an example from my recent project. I have managed this with a single livewire component.
In Livewire Component;
public $entries = [];
public $date;
public function mount()
{
$this->date = now()->format('Y-m-d');
$this->entries=[
[
'name'=>'',
'amount'=>'',
],
[
'name'=>'',
'amount'=>'',
]
}
Now, in edit.blade.php ;
<input type="date" wire:model="date">
#foreach($entries as $key=>$entry)
<div wire:key="{{'entry'.$key}}">
<div>
<input type="text" wire:model="entries.{{$key}}.name">
</div>
<div>
<input type="number" wire:model="entries.{{$key}}.amount">
</div>
</div>
#endforeach
Now, again in livewire component for saving;
public function save()
{
foreach($this->entries as $entry){
Transaction::create([
'name'=>$entry['name'],
'amount'=>$entry['amount']
)];
}
//Notify User
}
However, if for any reason you need two livewire component to manage a same form, you can emit from a component and listen in another component.
For example in emitting component;
public function save(){
$this->emit('entryMade', $amount);
}
Now in listening component;
protected $listeners = ['entryMade'];
public function entryMade($amount)
{
// Do anything with $amount
}

laravel foreach input radiobutton displayed incorrectly

I'm trying to display the options for the questions. i have the problem that when im doing it this way:
#section('content')
<div class="card">
<div class="card-header">Quiz: {{$category->name}}:</div>
<div class="card-body">
<form action="#" method="post" class="form-group">
#csrf
#foreach($questions as $key => $question)
<div class="form-group">
<label for="question">Question {{1+$key}}:</label>
<p class="card-text">{{$question->question_text}}</p>
#foreach($question->option_text as $key => $option)
<input type="radio">{{$option}}
#endforeach
</div>
#endforeach
<div class="form-group">
<input type="submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
#endsection
i can check all radio buttons at the same time but if i put there a name for the radiobutton i can check only one of the options for the whole questions.. i think there's something strange with the foreach loop..
Info: the table "questions" has the following rows:
id, category_id, question_text, correct_answer, option_text (this is a json-field that is casted to an array)
Code from Controller:
public function store(Request $request, Category $category){
if($request->categoryTest == $category->name){
$questions = $category->question()->inRandomOrder()->get();
return view('user.test', compact('questions', 'category'));
}
}
do you have an idea how to fix this? thank you!
Try this:
#section('content')
<div class="card">
<div class="card-header">Quiz: {{$category->name}}:</div>
<div class="card-body">
<form action="#" method="post" class="form-group">
#csrf
#foreach($questions as $key => $question)
#php
$q = 1+$key
#endphp
<div class="form-group">
<label for="question">Question {{1+$key}}:</label>
<p class="card-text">{{$question->question_text}}</p>
#foreach($question->option_text as $key => $option)
<input name="radio-{{$q}}" type="radio">{{$option}}
#endforeach
</div>
#endforeach
<div class="form-group">
<input type="submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
#endsection
This seems to be a normal behavior of the radio buttons, only one is market at time. Have you tried to use checkbox instead?
Also, if you want to send it to backend, you'll need to set a name attribute. And here is the magic: instead of using a singular name, put it as array in order to get an array on your controller.
<input type="checkbox" name="question[]" class="btn btn-primary">

Cannot get request object

Grettings.
I'm trying to call an index view from itself, to look for a person and displaying results to the left.
But when I call the view and send data It always get null, could you please give me a clue. I've even called the store function and request is always null.
It should be a modal window to get the request object? What should I do If I wanted to show the windows as I'm doing it?
My routes
Route::get('registroaccesos/destinationSearchGet/', 'RegistroAccesosController#destinationSearchGet')->name('registroaccesos.destinationSearchGet');
Route::post('registroaccesos/destinationSearchPost/', 'RegistroAccesosController#destinationSearchPost')->name('registroaccesos.destinationSearchPost');
The controller
public function destinationSearchGet(){
$headData = array('pageTitle' => 'Admin Home - View all destinations');
return view('registroaccesos.index', $headData);
}
public function destinationSearchPost(Request $request){
$headData = array('pageTitle' => 'Admin Home - Search results');
$formData = $request->input('strPatron');
dd($formData);
// $data = ParentRegionList::destinationSearch($formData);
return view('registroaccesos.index', $headData);//->with(compact('data'))
}
The view
Part of the code of the view
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Acciones</span>
<a class="d-flex align-items-center text-muted" href="#">
<span data-feather="plus-circle"></span>
</a>
</h6>
<div class="form-group">
<label for="strSearch" class="col-form-label">Patrón de búsqueda</label>
<select name="strSearch" class="form-control">
<option value="1" selected> Código del usuario</option>
<option value="2" > Nombre del usuario</option>
</select>
</div>
<div class="form-group">
<input placeholder="Patrón de búsqueda"
id="strPatron"
required
name="strPatron"
spellcheck="false"
class="form-control"
value="Valor"
/>
</div>
<button class="btn btn-sm btn-outline-secondary"
onclick="
event.preventDefault();
document.getElementById('search-form').submit();
"
>Buscar</button>
<form id="search-form" action="{{ route('registroaccesos.store','el resultado' ) }}" method="POST" style="display: none;">
<!-- <input type="hidden" name="_method" value="delete">-->
{{ csrf_field() }}
</form>
The result
Well your <input> with name="strPatron" is not in your <form> so it will not get submitted when you submit the form. You need to have all the input elements inside the form or they won't get sent with the POST request.
The way you've got it right now only the CSRF field in your form is getting submitted. You can check this by doing a dd($request->all()) in your controller.

Categories