Validating multiple select box inside loop using laravel validation method - php

I have multiple select box with same name inside loop in a form. I have added laravel validation to check select box selected or not. But validation error message is showing for all the select boxes. Please check image attached. Any help would be appreciated.
cart.blade.php
#forelse($carts as $key => $cart)
<div class="col-sm-4 col-sm-4-booking1 form-group {{ $errors->has('guest.*.sleeps') ? ' has-error' : '' }}">
<label>Sleep(s)</label>
<select class="form-control form-control-booking1 jsBookCalSleep" name="guest[{{ $cart->_id }}][sleeps]">
<option value="">Choose Sleep(s)</option>
#for($i = 1; $i <= 30; $i++)
<option value="{{ $i }}" #if($i == $cart->sleeps) selected #endif>{{ $i }}</option>
#endfor
</select>
#if ($errors->has('guest.*.sleeps'))
<span class="help-block"><strong>{{ $errors->first('guest.*.sleeps') }}</strong></span>
#endif
</div>
#empty
<p>No bookings in your cart</p>
#endforelse
CartController.php
public function store(CartRequest $request)
{
dd($request->all());
}
CartRequest.php
public function rules()
{
return [
'guest.*.sleeps' => 'required|not_in:0'
];
}

Try these
#php
$inputName='guest.'.$cart->_id.'.sleeps';
#endphp
#if ($errors->has($inputName))
<span class="help-block"><strong>{{ $errors->first($inputName) }}</strong></span>
#endif
I didn't tested it,
If not working let me know

Solution: We can solve this issue by using two function. a.collect and b. contains. See the example below.
<select class="form-control m-bootstrap-select m_selectpicker"
name="generic_ids[]" data-live-search="true" multiple>
<option value="">Select Generic</option>
#foreach($generics as $generic)
<option value="{{$generic->id}}"
#if(collect(app()->request->generic_ids)->contains($generic->id))
selected
#endif
>{{$generic->title}}</option>
#endforeach
</select>
Code
Output

Related

Old value not setting properly on laravel 9 blade dropdown

In my laravel application I have a simple form with a dropdown.
Dropdown options are getting filled with DB data.
I want to populate my dropdown with user previously selected option on the edit.
Following is what I have done so far..
Blade
<select name="company_id" class="form-control">
#foreach($companies as $company)
#if (old('company_id') == $employee->company_id)
<option value="{{ $company->id }}" selected>{{ $company->name }}</option>
#else
<option value="{{ $company->id }}">{{ $company->name }}</option>
#endif
#endforeach
</select>
Controller.
public function edit(Employee $employee)
{
$companies = Company::all(['id','name']);
return view('employees.edit', compact('employee','companies'));
}
Employee Model
{
use HasFactory, Notifiable;
protected $fillable = [
'first_name', 'last_name', 'email', 'phone', 'company_id'
];
public function company()
{
return $this->belongsTo(Company::class);
}
}
My company table structure
Employee table structure
When I tried with these, it kept showing me the values in the dropdown on the edit but not setting the old value properly.....
Try this as your loop:
#foreach ($companies as $company)
<option value="{{ $company->id }}" {{ $company->id == old('company_id') ? 'selected' : '' }}>
{{ $company->name_en }}</option>
#endforeach
The reason could be typecasting.
#if (old('company_id') === $employee->company_id)
This will never be true. You see old holds string values and you're comparing it against an id which is of type int.
So, this will work for you:
#if ( (int)old('company_id') === $employee->company_id )
Also, there is a new directive you can use instead of conventional if-else statements checked :
#checked( old('key', $employee->key) )
#selected( old('key') === $employee->key )
In Laravel 9 you don't have to use if-else to check the value just use the #selected() blade function/directive.
<select name="company_id" class="form-control">
#foreach($companies as $company)
<option value="{{ $company->id }}" #selected(old('company_id') == $company->id)>{{ $company->name }}</option>
#endforeach
</select>
Also, we have the #checked() function as well:
<input type="checkbox" name="active" value="active" #checked(old('active', $user->active)) />

How to keep values in <select> after submitting a form in laravel 8

I have multiple <select> by city filter
select in blade
<select id="city" multiple name="city[]">
#foreach($cities as $city)
<option value="{{ $city->id }}">{{ $city->name }}</option>
#endforeach
</select>
Query for select
if ($request->has('industry')) {
$businessesQuery->whereIn('industry_id', $request->input('industry'));
}
try this
#if(request('type') != "")
$('#city').find('option[value="' + "{{request('type')}}" + '"]').attr('selected', true);
#endif
little manage according to your code then its should work

Determine selected options based on many-to-many relationship

I have three tables: products, categories and category_product.
In my edit form page I'm displaying the categories and subcategories values in a select box.
The chosen category options are saved in the pivot table category_product. This table has product_id and category_id.
Here's my code.
Product model
public function category() {
return $this->belongsToMany('App\Models\Category');
}
Category model:
public function products()
{
return $this->belongsToMany(Product::class);
}
edit product page view:
<select name="category_id[]" class="form-control" multiple size = 10>
#foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}">{{ $parentCategory->name }}</option>
#if(count($parentCategory->subcategory))
#include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
#endif
#endforeach
</select>
subcats-select view
#foreach($subcategories as $subcategory)
<option value="{{ $subcategory->id }}">---{{ $subcategory->name }}</option>
#if(count($subcategory->subcategory))
#include('includes.subcats-select',['subcategories' => $subcategory->subcategory])
#endif
</div>
#endforeach
How can I put "selected" attribute to the chosen category options, so when I edit the page to apply the changes properly?
You can get pivot table columns the following way:
Product model
public function category() {
return $this->belongsToMany('App\Models\Category')->withPivot('selected');
}
edit product page View:
<select name="category_id[]" class="form-control" multiple size = 10>
#foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}" selected="{{ $parentCategory->pivot->selected }}">
{{ $parentCategory->name }}
</option>
#if(count($parentCategory->subcategory))
#include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
#endif
#endforeach
</select>
EDIT: While the above answer might be helpful for others, it doesn't answer the question. So here's my second try after some clarification in the chat.
<select name="category_id[]" class="form-control" multiple size = 10>
#foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}"{{ $product->category->contains($parentCategory->id) ? 'selected' : '' }}>
{{ $parentCategory->name }}
</option>
#if(count($parentCategory->subcategory))
#include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
#endif
#endforeach
</select>

syntax error, unexpected ')' foreach laravel

I try looping variable with foreach in laravel but I get error
syntax error, unexpected ')'
Here my controller
public function getAdd()
{
$tahun_awal_bgt = 1990;
$tahun_skr_bgt = date('Y');
return view('laporan.posisikeuangan_laporan')->with([
'tahun_awal_bgt' => $tahun_awal_bgt,
'tahun_skr_bgt' => $tahun_skr_bgt]);
}
This my views
<div class="col-sm-2">
<select class="form-control">
<option>-- Semua --</option>
#foreach($tahun_awal_bgt <= $tahun_skr_bgt)
<option value="{{ $tahun_skr_bgt }}">{{ $tahun_awal_bgt }}</option>
{{ $tahun_awal_bgt++ }}
#endforeach
</select>
</div>
I still dont understand where I'am doing wrong, how do I fix this ?
Change this line in thr blade
#foreach($tahun_awal_bgt <= $tahun_skr_bgt)
To
#foreach($tahun_awal_bgt as $tahun_skr_bgt)
You should use for loop in your case:
#for($tahun_awal_bgt = $tahun_awal_bgt; $tahun_awal_bgt <= $tahun_skr_bgt; $tahun_awal_bgt++)
<option value="{{ $tahun_skr_bgt }}">{{ $tahun_awal_bgt }}</option>
<!-- No need for $tahun_awal_bgt++ here, i added in for loop -->
#endfor
Please note that i used #for and #endfor instead of #foreach and #endforeach, further there was no need to do {{ $tahun_awal_bgt++ }} in loop block is I already added it in #for loop declaration.
You should also learn how to use for and foreach loop in php
https://www.w3schools.com/php/php_looping_for.asp
Based on your confirmation at the comment before, you can follow this code to fix your problem.
#for($tahun_skr = $tahun_skr_bgt; $tahun_skr >= $tahun_awal_bgt; $tahun_skr--)
<option value="{{ $tahun_skr }}">{{ $tahun_skr }}</option>
#endfor

Laravel : Form select option value is always NULL when submitting

I have a form where I put de id's of my bands table inside a select option. When I select an id in the dropdownlist and try to submit the form, the value always remains NULL. How can I retrieve the value I selected?
create.blade.php file :
<form>
<select name="band_id">
#foreach ($bands as $band)
<option value="{{ $band->band_id }}">{{ $band->band_id }}</option>
#endforeach
</select>
<input type="submit" value="Submit">
</form>
My Bandcontroller inside my store action :
$bands->band_id = $input['band_id'];
First of all you are using #foreach ($band as $band), make sure it's not a typo and if not then fix it (Could be $bands as $band and assumed you know what I mean). Anyways, you may also try this:
{{ Form::select('band_id', $bands, Input::old('band_id')) }}
Just pass the $bands variable to the View and Laravel will create the SELECT for you, you don't need to loop manually. To retrieve the value, you may try this:
$band_id = Input::get('band_id');
Laravel 6 or above
//blade
{!!Form::open(['action'=>'CategoryController#storecat', 'method'=>'POST']) !!}
<div class="form-group">
<select name="cat" id="cat" class="form-control input-lg">
<option value="">Select App</option>
#foreach ($cats as $cat)
<option value={{$cat->id}}>{{ $cat->title }}</option>
#endforeach
</select>
</div>
<div class="from-group">
{{Form::label('name','Category name:')}}
{{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Category name'])}}
</div>
<br>
{!!Form::submit('Submit', ['class'=>'btn btn-primary'])!!}
{!!Form::close()!!}
// controller
public function storecat(Request $request){
Log::channel('stack')->info('name'.$request->app);
if($request->input('cat')==null){ // retriving option value by the name attribute of select tag
return redirect(route('cats.cat'))->with('error', 'Select an app');
}
$this->validate($request,[
'name'=>'required',
]);
}

Categories