in my form i have a select and if i edit i want keep select the option i try with isset but i dont know how to use it in a select
this is my select:
<div class="form-group">
<label for="id_raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza" placeholder="Raza">
#foreach ($razas as $raza)
<option value="{{$raza->id}}">{{ $raza->Nombre}}</option>
#endforeach
</select>
</div>
my controller:
public function edit($id)
{
//
$mascota=Mascota::findOrFail($id);
$razas = Raza::all();
$propietarios = Propietario::all();
return view('mascota.edit', compact('mascota', 'razas', 'propietarios'));
}
my table:
{
Schema::create('mascotas', function (Blueprint $table) {
$table->id();
$table->foreignId('id_raza')
->nullable()
->constrained('razas')
->nullOnDelete()
->cascadeOnUpdate();
$table->timestamps();
});
}
Since mascotas has a id_raza, this value is needed to be able to set the selected option.
#foreach ($razas as $raza)
#if (!empty($moscatas->id_raza) && $moscatas->id_raza == $raza->id)
<option value="{{$raza->id}}" selected>{{ $raza->Nombre}}</option>
#else
<option value="{{$raza->id}}">{{ $raza->Nombre}}</option>
#endif
#endforeach
You can also do it like this,
<option value="{{ $raza->id }}" {{
$raza->id == $moscatas->id_raza ?
'selected' : '' }}>
{{ $raza->Nombre}
</option>
Related
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)) />
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>
I have two tables, SALARIE and CHANTIER, between them the relationship hasMany BelongsTTO, chantier1 (salarie1, salarie2, salarie3...), in my blade I have two selections, I want when I choose in select 1(chantier) to the the 2nd select(salaries) fill in with salaries of Chantier chosen.
SalarieController
public function pointage()
{
$chantiers = Chantier::all();
return view('pointage', ['chantiers' => $chantiers]);
}
pointage.blade.php
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<div class="form-group ">
<label>chantier:</label>
<select class="form-control" #change="onChange">
#foreach($chantiers as $chantier)
<option value="{{ $chantier->id }}">{{ $chantier->nomC }} {{ $chantier->id }}</option>
#endforeach
</select>
</div>
<div class="form-group ">
<label>salarie:</label>
<select class="form-control" #change="onChange">
#foreach($salaries as $salarie)
<option value="{{ $salarie->id }}">{{ $salarie->nomS }} </option>
#endforeach
</select>
</div>
</div>
vuejs code
const app = new Vue({
el: "#app",
data: function() {
return {
message: "Vue"
}
},
methods: {
onChange(event) {
}
}
})
Route
Route::get('pointage', 'SalarieController#pointage');
You can define computed variable salaries and on chantiers changes make request and if done fill salaries with response data and instead of using laravel's for each use v-for="salary in salaries.
Hope it help u.
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
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',
]);
}