I want to get data to the dropdown by using another dropdown in the same page - laravel

I have a dropdown on my page to load districts. And I have another dropdown to load Divisions according to that selected district. The below code I have got all the divisions. But I want only the divisions according to the selected districts. How can I do?
#php
$districtAll=\App\District::all();
#endphp
<div class="row">
<label class="col-md-4 control-label" for="district">9. District</label>
<div class="col-md-8">
<select name="district">
<option type="text" class="detail-wp" value="">Select District</option>
#foreach($districtAll as $all)
<option value="{{$all->DISTRICT_ID}}">{{$all->DISTRICT}} </option>
#endforeach
</select>
</div>
</div>
<br>
#php
$getDsAll=\App\DsDivision::all();
#endphp
<div class="row">
<label class="col-md-4 control-label" for="ds_division">10. DS Division</label>
<div class="col-md-8">
<select name="ds_division" class="form-control">
<option type="text" class="detail-wp" value=""></option>
#foreach($getDsAll as $all)
<option value="{{$all->DIVISION_ID}}">{{$all->DIVISION}} </option>
#endforeach
</select>
</div>
</div>

You can do it using ajax request:
$('select[name=district]').on('change', function(){
$districtId = $(this).val();
$.get('/division/district/'+$districtId).done(function(res){
$.each(res, function (key, value) {
$('select[name=ds_division]').append(`<option value='` + value.id + `'>` + value.name +`</option>`);
});
});
to make this working you will need a route like
Route::get("/division/district/{district}", "DivisionController#getByDistrictId");
DivisionController#getByDistrictIdwill be
public function getByDistrictId($district)
{
return Division::where('district_id',$district)->get();
}
this code just to give you an idea of how you can do it.

Related

Livewire - Dependant Dropdown select

I have created a dependant dropdown with livewire like this:
class CreateAppointment extends Component
{
public $doctorCategories;
public $doctors;
public $selectedDoctorCategory = NULL;
public function mount(){
$this->doctorCategories = Doctor_Categories::all();
$this->doctors = collect();
}
public function updatedSelectedDoctorCategory($doctor_type_ID)
{
if(!is_null($doctor_type_ID)){
$this->doctors = Doctor_Categories::with('doctors')->find($doctor_type_ID);
}
}
}
And this is in my blade file:
<div class="form-group row">
<label for="doctor_categories" class="col-md-4 col-form-label text-md-right">Doctor Categories</label>
<div class="col-md-6">
<select wire:model="selectedDoctorCategory" class="form-control">
<option value="">Choose category</option>
#foreach($doctorCategories as $cat)
<option value="{{ $cat->id }}">{{ $cat->doctor_category }}</option>
#endforeach
</select>
</div>
</div>
#if (!is_null($selectedDoctorCategory))
<div class="form-group row">
<label for="doctor" class="col-md-4 col-form-label text-md-right">Doctor</label>
<div class="col-md-6">
<select class="form-control" name="doctor_id">
<option value="" selected>Choose Doctor</option>
#foreach($doctors->doctors as $doctor)
<option value="{{ $doctor->id }}">{{ $doctor->name }}</option>
#endforeach
</select>
</div>
</div>
#endif
</div>
It works well but when i select "Choose category" again it throws an error saying attempted to read property doctors on null.How can i avoid this?
The issue here is, that livewire does not apply the TrimStrings and ConvertEmptyStringsToNull middlewares on its requests. This is by design and is not a bug. It can be reintroduced (see the comments to the linked issue) but I advise caution doing so. With select it should work fine, but with input it can mess things up.
Instead of checking for is_null, check for empty and you should be fine.

How to filter subcategory data from parent category in Laravel8

I want to filter subcategory data according to parent category.
I am getting all my subcategory inside all the categories. I tried many old answers from stackoverflow and youtube but not worked.
I want this filter inside my article post form.
create.article.blade.php
<form action="{{ URL::to('post-article-form') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="exampleInputEmail1">Article Name <b style="color: red">*</b></label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter article title" name="articleTitle" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Select Article category </label>
<select class="form-control" name="category" id="category" required>
<option value=""> Select </option>
#foreach($categories as $category)
<option value="{{ $category->id }}"> {{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Select Sub category </label>
<select class="form-control" name="subCategory" id="subCategory" required>
<option value=""> Select </option>
#foreach($subCategories as $subCategory)
<option value="{{ $subCategory->id }}"> {{ $subCategory->name }}</option>
#endforeach
</select>
</div>
I used this below script for filter but not worked.
<script>
$('#category').on('change',function(e){
console.log(e);
var cat_id = e.target.value;
//ajax
$.get('/ajax-subcat?cat_id='+cat_id, function(data){
//subcategory
$('#subCategory').empty();
$('#subCategory').append($("<option></option>").val("").html("--Select Sub Category--"));
$.each(data,function(index, subcatObj){
$('#subCategory').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
})
})
});
</script>
My web.php route
//sub category
Route::get('add-sub-category', [SubCategoryController::class, 'create']);
Route::post('post-sub-category-form', [SubCategoryController::class, 'store']);
Route::get('subcategories', [SubCategoryController::class, 'index']);
Route::get("/ajax-subcat", function (Request $request){
$cat_id = $request-> Input::get('cat_id');
$subCategories = SubCategory::where('category_id',$cat_id)->get();
return response()->json($subCategories);
});

Laravel Error during update - Undefined variable: id

I am working on a project using Laravel-5.8
protected $table = 'ratings';
protected $fillable = [
'rating_type',
'rating_value',
'rating_description',
];
public function rules()
{
return [
'rating_type' => 'required|numeric|min:1|max:10|unique:appraisal_ratings,rating_type,company_id'.$this->id,
];
}
The rating has an id column, and that's the primary key. Why I checked it against company_id is that different companies can have the same rating type.
Controller
public function edit($id)
{
$rating = Rating::where('id', $id)->first();
return view('ratings.edit')
->with('rating', $rating)
->with('rating_types', $this->rating_types)
->with('rating_descriptions', $this->rating_descriptions)
->with('rating_values', $this->rating_values);
}
public function update(UpdateRatingRequest $request, $id)
{
$rating = Rating::find($id);
$rating->rating_type = $request->rating_type;
$rating->rating_value = $request->rating_value;
$rating->rating_description = $request->rating_description;
$rating->save();
Session::flash('success', 'Rating is updated successfully');
return redirect()->route('ratings.index');
}
edit.blade
<form action="{{route('ratings.update', ['id'=>$rating->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating" tabindex="1" name="rating_type" style="width: 100%;">
<option value="">Select Rating</option>
#foreach($rating_types as $k => $rating_type)
<option value="{{$k}}" #if($rating->rating_type == $k) selected #endif>{{$rating_type}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Description:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Description" tabindex="1" name="rating_description" style="width: 100%;">
<option value="">Select Description</option>
#foreach($rating_descriptions as $k => $rating_description)
<option value="{{$k}}" #if($rating->rating_description == $k) selected #endif>{{$rating_description}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating Score:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating Score" tabindex="1" name="rating_value" style="width: 100%;">
<option value="">Select Rating Score</option>
#foreach($rating_values as $k => $rating_value)
<option value="{{$k}}" #if($rating->rating_value == $k) selected #endif>{{$rating_value}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('ratings.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
When I clicked on the save button to update, I got this error:
rating_type already exists.
That error should not have occured since I am doing update.
How do I resolve it?
Thank you.
You are checking the unique on update wrong
Unique Rule Usage
unique:table,column,except,idColumn
* 3rd param is for value for column to except and 4th is for column to except
Fix
//App\Http\Requests\UpdateRatingRequest
'rating_type' => 'required|numeric|min:1|max:10|unique:table_name,rating_type,table_primary_key'.$this->id,

show data of nested foreach loop in two different Select Tag in laravel

I have two Model(Category,Brand) are relate with one to many relation(hasMany) in laravel, Like category hasMany brands. now i want to display brand data in one select tag and category model data in another select tag.
Here is my Controller code
$category=Category::with('brands')->get();
return view('product.add')->with('category',$category);
Here is my view blade.
<div class="form-group">
<select name="category_id" class="input">
<option value="">Select Main Category</option>
#foreach($category as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<select name="brand_id" class="input">
#foreach($brands->brands as $brand)
<option value="{{$brand->id}}">{{$brand->name}}</option>
#endforeach
</select>
</div>
its not working
You can do something simple like this:
<div class="form-group">
<select name="category_id" class="input">
<option value="">Select Main Category</option>
#foreach($category as $cat)
<option value="{{$cat>id}}">{{$cat->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<select name="brand_id" class="input">
#foreach($category as $cat)
#foreach($cat->brands as $brand)
<option value="{{$brand->id}}" category="{{$cat->id}}">{{$brand->name}}</option>
#endforeach
#endforeach
</select>
</div>
and you need to show only the brands for the selected option using javascript(jquery)
$('[name="category_id"]').on('change',function() {
if($(this).val() != '') {
$('[name="brand_id"] option').hide();
$('[name="brand_id"] option[category="'+$(this).val()+'"]').show();
} else {
$('[name="brand_id"] option').show();
}
});

Can't make multiple select in registration form

I use the basic registration form but I want to add a multiple select, a User can have multiple Skills and select them when he register.
My problem is that when I select multiples values Laravel only take the last one, so I search on the web for a solution and they say to add [] after my class name, so this is what I do :
<div class="form-group row">
<div class="col-md-6">
<?php $competences = \App\Competence::all(); ?>
<select name="competences[]" multiple="" class="form-control">
<option value="" selected disabled style="display:none">choose your school</option>
#foreach ($competences as $competence)
<option value="{{ $competence->id }}">{{ $competence->name }}</option>
#endforeach
</select>
</div>
</div>
But now, when I submit the form the page reload and stay in the register form, and the user is not register... I don't know what to do, anyone of you have a solution ?
Here is how I check the competences in my registerController
$competences = $data['competences'];
foreach ($competences as $comp){
$user->competences()->save(Competence::find($comp));
}
Use multiple="multiple" OR just multiple in blade.php:
<div class="form-group row">
<div class="col-md-6">
<?php $competences = \App\Competence::all(); ?>
<select name="competences[]" class="form-control" multiple>
<option value="" selected disabled style="display:none">choose your school</option>
#foreach ($competences as $competence)
<option value="{{ $competence->id }}">{{ $competence->name }}</option>
#endforeach
</select>
</div>
</div>
then in your controller, verify that you're actually getting the data in the form of an array by just printing $data
return $data;

Resources