Load dependent dropdown on Edit Laravel - laravel

How to automatically load or retrieve the subcategory/dependent dropdown based on the selected value of parent dropdown in Edit. If I click the edit, the doctor should instantly load. I've been searching for hours for the solutions please help.
Blade
<select name="clinic_id" data-placeholder="Search" data-allow-clear="true"
class="form-control select2bs4" style="width: 100%;" id="load_clinic">
<option selected="selected"></option>
#foreach ($clinic as $id => $item)
<option value="{{ $id }}"
{{ $schedule->clinic_id == $id ? 'selected' : '' }}>
{{ $item }}
</option>
#endforeach
</select>
<select name="doctor_id" data-placeholder="Search" data-allow-clear="true"
class="form-control select2bs4" style="width: 100%;" id="load_doctor">
</select>
Javascript
$(document).ready(function() {
$('#load_clinic').on('change', function(e) {
var clinic_id = e.target.value;
if (clinic_id) {
$.ajax({
url: "{{ route('getDoctor') }}",
type: "POST",
data: {
clinic_id: clinic_id,
_token: "{{ csrf_token() }}"
},
success: function(data) {
if (data) {
$('#load_doctor').empty();
$('#load_doctor').append(
'<option value=""> Select Doctor</option>');
$.each(data, function(key, value) {
$('#load_doctor').append($(
"<option/>", {
value: key,
text: value
}));
});
} else {
$('#load_doctor').empty();
}
}
})
} else {
$('#load_doctor').empty();
}
});
});
Controller
public function edit($id)
{
$schedule = Schedule::findOrFail($id);
$clinic = Clinic::pluck('name', 'id');
$doctor = Doctor::get()->pluck('full_name', 'id');
return view('admin.schedule.edit', compact('schedule', 'doctor', 'clinic'));
}
public function getDoctor(Request $request)
{
$id = $request->clinic_id;
$doctor = Doctor::where('clinic_id', $id)->get()->pluck('full_name', 'id');
return response()->json($doctor);
}

You can get initial select options with PHP before resorting to ajax.
Consider using plural nouns when you are using get() and singular when using i.e. first()
Also, consider using #if(condition) #endif instead of ternary operators in blade
This is solution with PHP, if you want to get doctors with AJAX, in addition to onChange listener, you should also call it when page loads,
Controller
public function edit($id)
{
$schedule = Schedule::findOrFail($id);
$clinic = Clinic::pluck('name', 'id');
$doctor = Doctor::where('clinic_id', $schedule->clinic_id)->get();
return view("admin.schedule.edit", compact('schedule', 'doctor', 'clinic'));
}
Blade
<select name="clinic_id" data-placeholder="Search" data-allow-clear="true"
class="form-control select2bs4" style="width: 100%;" id="load_clinic">
<option selected="selected"></option>
#foreach ($clinic as $id => $item)
<option value="{{ $id }}"
{{ $schedule->clinic_id == $id ? 'selected' : '' }}>
{{ $item }}
</option>
#endforeach
</select>
<select name="doctor_id" data-placeholder="Search" data-allow-clear="true"
class="form-control select2bs4" style="width: 100%;" id="load_doctor">
#foreach($doctor as $item)
<option value="{{$item->id}}">{{$item->full_name}}</option>
#endforeach
</select>

Related

Insert a Form value from a select in a dynamic url

While using laravel to create a movie catalog, I am trying to extract the value from an HTML Form and insert it in the URL.
The objective is that, from the main page which is:
http://127.0.0.1:8000/index/
I want it to extract an ID value from the form and insert it in the url:
http://127.0.0.1:8000/index/1
http://127.0.0.1:8000/index/2
http://127.0.0.1:8000/index/3
As each one is a dynamic view that will display each movie information from the database.
The form is already recognizing the ids and is displaying them in the select form in page, but I am not able to have that value used to insert it in the url as shown above.
Please help me, here is my code:
index.blade.php
<form action=" WHAT TO PLACE HERE??? " method="POST">
#csrf
<select name="selector">
<option value="" disabled selected> --- ID --- </option>
#foreach($movies as $movie)
<option value="{{ $movie->id }}">{{ $movie->id }}</option>
#endforeach
</select>
<button>Buscar</button>
</form>
web.php
Route::get('/index', 'App\Http\Controllers\MovieController#index');
Route::get('/index/create','App\Http\Controllers\MovieController#create');
Route::post('/index','App\Http\Controllers\MovieController#store');
Route::get('/index/{id}','App\Http\Controllers\MovieController#show');
Route::delete('/index/{id}','App\Http\Controllers\MovieController#destroy');
MovieController.php
class MovieController extends Controller
{
public function index() {
$movies = Movie::all();
return view('movies.index', ['movies' => $movies,]);
}
public function show($id) {
$movie = Movie::findOrFail($id);
return view('movies.show', ['movie' => $movie]);
}
public function create() {
return view('movies.create');
}
public function store(){
$movie = new Movie();
$movie->title = request('title');
$movie->synopsis = request('synopsis');
$movie->year = request('year');
$movie->cover = request('cover');
$movie->save();
return redirect('/')->with('mssg','La pelĂ­cula a sido registrada');
}
public function destroy($id) {
$movie = Movie::findOrFail($id);
$movie->delete();
return redirect('/index/');
}
}
Replace you form as:
index.blade.php
<form action="" method="POST" id="form_id">
#csrf
<select name="selector" id="selector">
<option value="" disabled selected> --- ID --- </option>
#foreach($movies as $movie)
<option value="{{ $movie->id }}">{{ $movie->id }}</option>
#endforeach
</select>
<button type="submit">Buscar</button>
</form>
Add script after this :
<script>
$('#selector').change(function(){
var selected_value = $(this).val();
$('#form_id').attr('action', 'http://127.0.0.1:8000/'+selected_value);
});
</script>
This will set your action dynamic as per selection with your select tag

How to build conditional list of dropdown options in Laravel Voyager

I have a problem with Laravel Voyager v1.2. I need to filter list of related list of options in select dropdown easily by where condition. So let's say I have Post with relation to Category, but I don't want to list all Categories in select dropdown, but just that active ones.
I tried to force Voyager to take my own method to build an relationship in Post model:
public function category_id() {
return $this->belongsTo('Post::class')->where('active',1);
}
Also tried to define scope in BREAD JSON options for the category field:
{
"relationship": {
"key": "id",
"label": "name",
"scopes": [
"active"
]
}
}
Post Model part:
public function scopeActive($query) {
return $query->where('active', 1);
}
This is how my Post class look like (I don't actualy need to filter active categories, but food categories by it's IDs):
public function soup1() {
return $this->belongsTo('App\Meal')->where('meal_category_id',1);
}
public function soup2() {
return $this->belongsTo('App\Meal')->where('meal_category_id',1);
}
public function mealy() {
return $this->belongsTo('App\Meal')->where('meal_category_id',7);
}
public function scopeSoups($query)
{
return $query->where('meal_category_id', 1);
}
public function scopeMealy($query)
{
return $query->where('meal_category_id', 7);
}
I want to receive filtered list of options instead of all model rows.
You can do this easily by overriding the blades in voyager:
Step 1 :
Copy relationship.blade.php
from: /"YourProject"/vendor/tcg/voyager/resources/views/formfields/relationship.blade.php
To: /"YourProject"/resources/views/vendor/voyager/formfields/relationship.blade.php
This way voyager will use this file in your your project views instead of the package file in the vendor.
Read More: Voyager Documentations
Step 2 :
In the line 25 of relationship.blade.php you'll see this block of code:
<select
class="form-control select2-ajax" name="{{ $options->column }}"
data-get-items-route="{{route('voyager.' . $dataType->slug.'.relation')}}"
data-get-items-field="{{$row->field}}"
>
#php
$model = app($options->model);
$query = $model::where($options->key, $dataTypeContent->{$options->column})->get();
#endphp
#if(!$row->required)
<option value="">{{__('voyager::generic.none')}}</option>
#endif
#foreach($query as $relationshipData)
<option value="{{ $relationshipData->{$options->key} }}" #if($dataTypeContent->{$options->column} == $relationshipData->{$options->key}){{ 'selected="selected"' }}#endif>{{ $relationshipData->{$options->label} }}</option>
#endforeach
</select>
Which you should override it with this:
#if($options->table == 'categories')
<div class="ap-form-input">
#php
$model = app($options->model);
$query = $model::where('active', true)->get();
#endphp
<select class="form-control select2" id="language-select" name="{{ $options->column }}">
#if(!$row->required)
<option value="">{{__('voyager::generic.none')}}</option>
#endif
#foreach($query as $relationshipData)
<option value={{ $relationshipData->{$options->key} }} #if($dataTypeContent->{$options->column} == $relationshipData->{$options->key}){{ 'selected="selected"' }}#endif>{{ $relationshipData->{$options->label} }}</option>
#endforeach
</select>
</div>
#else
<div class="ap-form-input">
<select class="form-control select2" name="{{ $options->column }}">
#php
$model = app($options->model);
$query = $model::all();
#endphp
#if(!$row->required)
<option value="">{{__('voyager::generic.none')}}</option>
#endif
#foreach($query as $relationshipData)
<option value={{ $relationshipData->{$options->key} }} #if($dataTypeContent->{$options->column} == $relationshipData->{$options->key}){{ 'selected="selected"' }}#endif>{{ $relationshipData->{$options->label} }}</option>
#endforeach
</select>
</div>
#endif
This way when you're using categories relationship you will only get the active categories.
Click on the link and follow these simple steps, just now I solved my issue.
https://voyager.readme.io/docs/relationships

Laravel Ajax dropdown example

can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax.
i have done it without ajax, but i don't know how to do with ajax.
without ajax:
<select name="nation_id" class="custom-select" >
<option selected value=" ">Choose...</option>
#foreach($nations as $nations)
<option value="{{#$nation_id}}" {{#$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{#$nations->nation}}</option>
#endforeach
Controller:
$nations = nation::all();
<select class="form-control" name="nation_id" id="nation_id">
<option value="">Select nation</option>
#foreach($nations as $nation)
<option value="{{ $nation->nation_id }}">{{ $nation->nation_name }} </option>
#endforeach
</select>
<select class="form-control" name="teacher" id="teacher">
</select>
now the ajax code:
<script type="text/javascript">
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getTeacher)}}/"+nid,
success:function(res)
{
if(res)
{
$("#teacher").empty();
$("#state").append('<option>Select Teacher</option>');
$.each(res,function(key,value){
$("#teacher").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
</script>
now in controller file;
public function getTeacher($id)
{
$states = DB::table("teachers")
->where("nation_id",$id)
->pluck("teacher_name","teacher_id");
return response()->json($teachers);
}
And last for route file:
Route::get('/getTeacher/{id}','TeachersController#getTeacher');
Hope this will work..
Good Luck...
Create a route for your method which will fetch all the nations-
Route::get('nations-list', 'YourController#method');
Create a method in your controller for the above route-
public function method()
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations)
}
Add a select box like this in your HTML-
<select id="nation_id" name="nation_id"></select>
If you want to auto select the option based on a variable then you can do this-
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">
And then add this script in your HTML to fetch the nation list on page load-
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id); // This will select the default value
});
});
</script>

Laravel 5 multi dynamic dropdown

I'm trying to use the data of the first dropdown, to fill the second.
An example here:
https://gitlab.com/Bons/laravel5.3_dynamic_dropdown/blob/master/readme.md
Controller functon return data, but second dropdown is empty.
First dropdown:
<span>Country: </span>
<select style="width: 200px" class="country" id="id_country">
<option value="0" disabled="true" selected="true">-Select-</option>
#foreach($countries as $contry)
<option value="{{$contry->id_country}}">{{$contry->name}}</option>
#endforeach
</select>
linked dropdown:
<label>City
<select id="region" class="form-control input-sm" name="region_id">
<option value=""></option>
</select>
</label>
Script:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.country',function(){
console.log("hmm its change");
var id=$(this).val();
console.log(id)
$.ajax({
type:'get',
url:'{!!URL::to('findRegions')!!}',
data:{'id':id},
success:function(data) {
console.log("success");
console.log(data.length);
console.log(data);
$.each(data, function(index,subCatObj){
// console.log(subCatObj.name)
$('#region').append(''+subCatObj.name+'');
});
},
error:function(){
console.log("error");
}
});
});
});
</script>
Route:
Route::get('/findRegions/','GirlsController#findRegions');
Controller function:
public function findRegions(Request $request){
$id=$request->id;
$regions=Region::select('name')
->where('id_country',$id)
->get();
dump($regions);
return $regions;
}
Here is how i did it,
in routes/web.php
Route::post('select-ajax', 'Main#selectAjax')->name('select-ajax');
in Controller : Main.php
public function __construct()
{
View::share('selectAllCountries', Country::pluck("name","id")->all());
}
public function selectAjax(Request $request)
{
if($request->ajax())
{
$getRegion = Region::where('id_country',$request->id)->pluck("nameOfTheRegion","id")->all();
$data = view('ajax-select',compact('getRegion'))->render();
return response()->json(['options'=>$data]);
}
}
then create a simple blade file name ajax-select.blade.php
<option selected disabled>--- Select Region---</option>
#if(!empty($getRegion))
#foreach($getRegion as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
#endif
Ajax call
{!! Form::select('country',[' '=>'--- Select Country ---']+$selectAllCountries,null,['class'=>'form-control']) !!}
{!! Form::select('region',[' '=>'--- Select Region---'],null,['class'=>'form-control']) !!}
<script>
$("select[name='country']").change(function(){
var id = $(this).val();
var token = $("input[name='_token']").val();
$.ajax({
url: "{{ route('select-ajax') }}",
method: 'POST',
data: {'id':id, '_token':token},
success: function(data) {
$("select[name='region']").html('');
$("select[name='region']").html(data.options);
},
error:function(){
alert("error!!!!");
}
});
});
</script>
Hope this helps

select box using AJAX

I have a select form which has three fields, Location, Estate and Size that populate dynamically using ajax.
When a user selects a town, the estates drop down options appear with respect to the town selected.
When the user clicks on search button, results based on the selection should appear.
According to my code, when I dd the variables $Estate and $Size in my post method, I get the values selected by the user on the form. This is what I want.
However, when I dd $Location, I get the id number instead of the value the user selected on the form.
This is my form :
<form class="form-inline" id="search-bar" action="{{route('post_index')}}" method="post">
{{ csrf_field() }}
<select class="form-control productcategory" name="Location" id="product_cat_id">
<option value="0" disabled="true" selected="true">Town</option>
#foreach($cities as $city)
<option value="{{$city->id}}">{{$city->product_cat_name}}</option>
#endforeach
</select>
<select class="form-control productname" name="Estate">
<option value="0" disabled="true" selected="true">Estate</option>
</select>
<select class="form-control" name="Size">
<option value="0" disabled="true" selected="true">Size</option>
<option value="Bedsitter">Bedsitter</option>
<option value="One Bedroom">One Bedroom</option>
<option value="Two Bedroom">Two Bedroom</option>
<option value="Three Bedroom">Three Bedroom</option>
</select>
<button type="submit" class="btn btn-default">Search</button>
</form>
This is my AJAX code :
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change', '.productcategory', function(){
//console.log("Shit is working");
var new_id=$(this).val();
//console.log(cat_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findEstateName')!!}',
data:{'id':new_id},
success:function(data){
//console.log('success');
console.log(data);
//console.log(data.length);
op+='<option value="0" selected disabled>chose estate</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].Estate+'">'+data[i].Estate+'</option>';
}
div.find('.productname').html(" ");
div.find('.productname').append(op);
},
error:function(){
}
});
});
$(document).on('change','.productname',function (){
var prod_id=$(this).val();
var a=$(this).parent();
console.log(prod_id);
var op="";
});
});
</script>
This is my post method :
public function postIndex(){
//echo "success";
$Location = Input::get('Location');
$Estate = Input::get('Estate');
$Size = Input::get('Size');
$validator= Validator::make(
array(
'Location'=>$Location,
'Estate'=>$Estate,
'Size'=>$Size
),
array(
'Location'=>'required',
'Estate'=>'required',
'Size'=>'required'
)
);
if ($validator->fails()) {
return redirect()->route('home-index')->withErrors($validator);
// echo "fail";
}else{
$houses=DB::table('houses')->where('Location', $Location)->where('Size', $Size)->where('Estate', $Estate)->get();
dd($Location);
//$towns = DB::table('houses')->pluck('Location', 'Location');
//$estates = DB::table('houses')->pluck('Estate', 'Estate');
$cities=ProductCat::all();
$data = [
'house' => $houses,
//'towns' => $towns,
//'estates' => $estates,
'cities' => $cities
];
//dd($data);
if (count($houses)) {
return View('pages.home', $data);
}else{
Session::flash('fail', 'Sorry, no results found...');
return View('pages.home',$data, ['FailMessage' => 'Sorry no results found..'])->withHouse($houses);
}
}
}
What do I need to do so that when I dd $Location, I get the Location name selected by the user?

Resources