I have in my form two dependant dropdowns based on the first select option.
When i am attempting to store to the DB i get the following problem....
Integrity constraint violation: 1048 Column 'service_id' cannot be null
Can someone help me identify where my problem is and how to fix, i think it is related to my store method because the dependant dropwdowns
Here is how i pass to the view:
$services = \DB::table('services')->lists("name", "id");
return view ('reservations', compact('services'));
Here is my form in view:
{!! Form::open(array("url"=>"bookings", "class"=>"form-horizontal")) !!}
<select name="service" class="form-control" style="width:350px">
<option value="">--- Select Service ---</option>
#foreach ($services as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
<br />
<label for="price">This cost for this service is:</label><br />
<select name="price">
<option id="price"></option>
</select><br />
<label for="time">This duration for this service is:</label><br />
<select name="time">
<option id="time"></option>
</select>
<br />
<br />
{!! Form::label("booking_date", "Enter Date", array("class"=>"col-md-2")) !!}
{!! Form::text("booking_date","",array("placeholder"=>"Enter Date", "class="=>"form-control")) !!}
<br />
<br />
{!! Form::label("booking_time", "Enter Time", array("class"=>"col-md-2")) !!}
{!! Form::text("booking_time","",array("placeholder"=>"Enter Time", "class="=>"form-control")) !!}
<br />
<br />
{!! Form::submit('Book', array("class"=>"btn btn-primary","id"=>"btn")) !!}
{!! Form::close() !!}
Here is the JS for dependant dropdowns:
$(document).ready(function() {
$('select[name="service"]').on('change', function() {
var serviceID = $(this).val();
if(serviceID) {
$.ajax({
url: '/myform/ajax/'+serviceID,
type: "GET",
dataType: "json",
success:function(data) {
$('option[id="price"]').empty();
$.each(data, function(key, value) {
$('option[id="price"]').append('<p value="'+ key +'">£'+ value +'</p>');
});
}
});
}else{
$('option[id="price"]').empty();
}
});
});
$(document).ready(function() {
$('select[name="service"]').on('change', function() {
var serviceID = $(this).val();
if(serviceID) {
$.ajax({
url: '/serviceTime/ajax/'+serviceID,
type: "GET",
dataType: "json",
success:function(data) {
$('option[id="time"]').empty();
$.each(data, function(key, value) {
$('option[id="time"]').append('<p value="'+ key +'">'+ value +' minutes</p>');
});
}
});
}else{
$('option[id="time"]').empty();
}
});
});
Here is my controller store method:
public function store(Request $request)
{
//
$data = \Input::only("booking_date", "booking_time");
$bookings = new Booking($data);
$bookings->user_id = auth()->user()->id;
$bookings->service_id = $request->get('serviceID');
$bookings->service_price = $request->get('price');
$bookings->booking_date = $request->get('booking_date');
$bookings->booking_time = $request->get('booking_time');
$bookings->save();
return redirect('/');
}
in the model:
protected $fillable = ['service_price', 'service_time','booking_date', 'booking_time'];
Super simple, there is a field in your database called service_id that must be filled and have a value.
In your php, you expect form field called serviceID, but in your html you call it service.
<select name="service" class="form-control" style="width:350px">
Different names, so change one of them to the other.
Your selection form field name 'service' but you try to get value using $request->get('serviceID') that's why your got error.
Replace your store method.
public function store(Request $request,int $service)
{
//
$data = \Input::only("booking_date", "booking_time");
$bookings = new Booking($data);
$bookings->user_id = auth()->user()->id;
$bookings->service_id = $request->get('service');
$bookings->service_price = $request->get('price');
$bookings->booking_date = $request->get('booking_date');
$bookings->booking_time = $request->get('booking_time');
$bookings->save();
return redirect('/');
}
Or replace 4th line of your store method with
$bookings->service_id = $request->get('service');
Related
Hello everyone i need help.
I make dynamic dependent dropdown in Laravel 8, when create data it's work, but when i will edit data, dependent dropdown not selected in view edit.
My code like this,
view.blade
<label class="font-label">Provinsi</label>
<select name="prov_ktp" id="prov_ktp" class="form-control forms-input">
<option value="">Pilih Provinsi</option>
#foreach ($provinsi as $key => $prov)
<option value="{{ $key }}">{{ $prov }}</option>
#endforeach
</select>
<label class="font-label">Kota/Kabupaten</label>
<select name="kab_ktp" id="kab_ktp" class="form-control forms-input">
<option value="">Pilih Kota/Kabupaten</option>
</select>
<script>
$('#prov_ktp').change(function() {
var provinsiID = $(this).val();
if (provinsiID) {
$.ajax({
type: "GET",
url: "{{ url('get-kabupaten') }}?id_provinsi=" + provinsiID,
success: function(res) {
if (res) {
$('#kab_ktp').empty();
$('#kab_ktp').append('<option value="">Pilih Kota/Kabupaten</option>');
$.each(res, function(key, value) {
$('#kab_ktp').append('<option value="' + key + '">' + value + '</option>');
});
} else {
$('#kab_ktp').empty();
}
}
});
} else {
$('#kab_ktp').empty();
$('#kec_ktp').empty();
}
});
</script>
myController
// function display provinsi
public function showDalamNegeri() {
$provinsi = Provinsi::pluck('nama_provinsi', 'id_provinsi');
return view('data_pribadi.dalam_negeri', compact('provinsi'));
}
// function display kabupaten
public function getKabupaten(Request $request) {
$kabupaten = Kabupaten::where('id_provinsi', $request->id_provinsi)->pluck('nama_kabupaten', 'id_kabupaten');
return response()->json($kabupaten);
}
Route for display Kabupaten
Route::get('get-kabupaten', [DataPribadiController::class, 'getKabupaten'])->name('getKabupaten');
Thanks.
Hye everyone! First of all, my coding all about dynamic dropdown value, the issues now is the second dropdown value is not save inside the database. Which part did I missed or wrong?
View:-
<div class="col-md-3">
<select class="shiftPatternID" name="inputShiftPatternID" id="inputShiftPatternID" required style="width: 100%">
<option value="" hidden disabled selected>Please Select</option>
#foreach ($shiftpattern as $singleshiftpattern)
<option value="{{ $singleshiftpattern->id }}">{{ $singleshiftpattern->id }} - {{ $singleshiftpattern->code }}</option>
#endforeach
</select>
</div>
<div class="col-md-3">
<select class="sapCode" name="inputSapCode" id="inputSapCode" required style="width: 100%">
<option value="0" disabled="true" selected="true">Please Select</option>
</select>
</div>
View for second dropdown using jquery script:-
$(document).ready(function() {
$(document).on('change','.shiftPatternID',function() {
var cat_id=$(this).val();
var div=$(this).parent().parent().parent();
var op=" ";
$.ajax({
type: 'get',
url: '{!! URL::to('findSapCode') !!}',
data: {
'id':cat_id
},
success: function(data) {
op+='<option value="0" selected disabled>Please Select</option>';
for (var i=0;i<data.length;i++) {
op += '<option value="'+data[i].id+'">'+data[i].code+' - '+data[i].description+'</option>';
}
$('.sapCode').html('') ;
$('.sapCode').append(op);
},
error: function() {
}
});
});
});
Controller:-
public function store(Request $req)
{
$var_shift_pattern_id = $req ->inputShiftPatternID;
$var_sap_code = $req ->inputSapCode;
$usp_var = new UserShiftPattern;
$usp_var-> shift_pattern_id = $var_shift_pattern_id;
$usp_var-> sap_code = $var_sap_code;
$usp_var->save();
$execute = UserHelper::LogUserAct($req, "User Work Schedule Management", "Create User Work Schedule " .$req->inputUserID);
$feedback_text = "Successfully created User Work Schedule ".$req->inputUserID.".";
$feedback_title = "Successfully Created";
return redirect(route('usp.index', [], false))
->with([
'feedback' => true,
'feedback_text' => $feedback_text,
'feedback_title' => $feedback_title
]);
}
Routes:-
Route::get('/findSapCode','Admin\UserShiftPatternController#findSapCode');
Route::get('/admin/usershiftpattern', 'Admin\UserShiftPatternController#index')->name('usp.index');
Route::post('/admin/usershiftpattern/add', 'Admin\UserShiftPatternController#store')->name('usp.store');
Route::post('/admin/usershiftpattern', 'Admin\UserShiftPatternController#index')->name('usp.index');
The issue is with option value wrongly passed in jquery.It should be data[i].code instead of data[i].id
op+='<option value="'+data[i].code+'">'+data[i].code+" "+data[i].description+'</option>'
Also you might need to update query as well to show description
$data=ShiftPattern::select('code','id','description')->where('id',$request->id)->take(100)->get();
I am new to Ajax. So, excuse my lack of knowledge. When I pass the data in the view, I get IDs in my database. Even though I passed text from a dropdown dependent menu is that possible with explanation!
Please see those 2 tables category
and products
I wanted to get the names from category ('Désignation' => first table) in my view - but instead I got the IDs. Please help.
controller
public function create() {
$prod=ProductCat::all();
return view('Achats.create',compact('prod'));
}
public function findProductName(Request $request) {
$data = Product::select('Désignation','id') -> where('catégorie', $request->id) -> take(100) -> get();
return response()->json($data);
}
public function findRef(Request $request) {
$p = Product::select('Référence')->where('id',$request->id)->first();
return response()->json($p);
}
Routes
Route::get('create','AchatController#create')->name('create.Achat');
Route::get('/findProductName','AchatController#findProductName');
Route::get('/findRef','AchatController#findRef');
View
<form action="{{ route('Achat.store')}}" method="POST" enctype="multipart/form-data">
<span>Product Category: </span>
<select style="width: 200px"class="form-control catégorie" name="catégorie" id="catégorie" >
<option value=" " disabled="true" selected="true">-Select-</option>
#foreach($prod as $cat)
<option value="{{$cat->id}}">{{$cat->Désignation}}</option>
#endforeach
</select>
<span>Product Name: </span>
<select name ="Désignation" class="form-control Désignation" id="Désignation" style="width: 200px" >
<option value="" disabled="true" selected="true">Product Name</option>
</select>
<span>Product ref: </span>
<input name="Référence" id="Référence" class="form-control Référence" type="text" >
<br>
ajax
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.catégorie',function(){
// console.log("hmm its change");
var cat_id=$(this).val();
// console.log(cat_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findProductName')!!}',
data:{'id':cat_id},
success:function(data){
//console.log('success');
//console.log(data);
//console.log(data.length);
op+='<option value="0" selected disabled>chose product</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id+'">'+data[i].Désignation+'</option>';
}
div.find('.Désignation').html(" ");
div.find('.Désignation').append(op);
},
error:function(){
}
});
});
$(document).on('change','.Désignation',function () {
var prod_id=$(this).val();
var a=$(this).parent();
console.log(prod_id);
var op="";
$.ajax({
type:'get',
url:'{!!URL::to('findRef')!!}',
data:{'id':prod_id},
dataType:'json',//return data will be json
success:function(data){
console.log("Référence");
console.log(data.Référence);
// here price is column name in products table data.coln name
a.find('.Référence').val(data.Référence);
},
error:function(){
}
});
});
});
It looks like you are passing the Id as the value, hence the reason for getting the Id in your database table.
Change
#foreach($prod as $cat)
<option value="{{$cat->id}}">{{$cat->Désignation}}</option>
#endforeach
To
#foreach($prod as $cat)
<option value="{{$cat->Désignation}}">{{$cat->Désignation}}</option>
#endforeach
That should help.
In my Laravel-5.8, I passed data from controller to view using JSON.
I am using Laravel-5.8 for a web application project.
I am trying to make my dropdown load value on a textbox on change.
public function findScore(Request $request)
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
$child = DB::table('appraisal_goal_types')->where('company_id', $userCompany)->where('id',$request->id)->first();
$parentid = DB::table('appraisal_goal_types')->select('parent_id')->where('company_id', $userCompany)->where('id',$request->id)->first();
if(empty($child))
{
abort(404);
}
$weightedscore = DB::table('appraisal_goals')->select(DB::raw("SUM(weighted_score) as weighted_score"))->where('appraisal_identity_id', $identities)->where('employee_id', $userEmployee)->where('parent_id', $parentid)->get();
$maxscore = DB::table('appraisal_goal_types')->select('max_score')->find($child->parent_id);
return response()->json([
'maxscore' => $maxscore->max_score,
'weightedscore' => $weightedscore
]);
}
I send the max_score and weighted_score as JSON.
route:
Route::get('get/findScore','Appraisal\AppraisalGoalsController#findScore')->name('get.scores.all'); view blade
<form action="{{route('appraisal.appraisal_goals.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option hidden value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<input type="text" id="max_score" class="form-control" >
<input type="text" id="weighted_score" class="form-control" >
</form>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#goal_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
console.log("Its Change !");
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
// console.log("price");
console.log(data.maxscore);
console.log(data.weightedscore);
$('#max_score').val(data.maxscore);
$('#weighted_score').val(data.weightedscore);
},
error:function(){
}
});
});
});
</script>
When I click on the dropdown on change the max_score is working perfectly, but the weighted_score is having error:
GET http://localhost:8888/peopleedge/get/findScore?id=2 500 (Internal Server Error).
Then I got this on my console:
and the textbox:
I need the direct value to be displayed on the text and not the JSON object as shown in the diagram. For example, only 60 in the textbox.
How do I get this resolved?
Thank you.
$weightedscore is an object, so you should do the same for $weightedscore what you do for $maxscore: add the attribute and not the object to the response.
Change $weightedscore to $weightedscore->weighted_score in the return part.
return response()->json([
'maxscore' => $maxscore->max_score,
'weightedscore' => $weightedscore->weighted_score
]);
You can output $weightedscore before returning it by using var_dump($weightedscore); or print_r($weightedscore); and then you will see that it is an object having an attribute called weighted_score as stated in your SELECT ... as() part of your SQL statement.
since it is array hence it will be
$('#max_score').val(data.maxscore['maxscore']);
$('#weighted_score').val(data.weightedscore['weightedscore'][0]);
['weightedscore']=keyname that you gave on the controller
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
// console.log("price");
console.log(data.maxscore);
console.log(data.weightedscore);
$('#max_score').val(data.maxscore['maxscore']);
$('#weighted_score').val(data.weightedscore['weightedscore'][0]);
},
error:function(){
}
});
I have three tables .. I want to get categories that are associated to a place.. so when I choose a place, it filters the categories and shows me the categories list of that place.
Many to many relationships are set.
----- ------------- ------------
place category_place category
------ -------------- ------------
id place_id id
name category_id name
-------------------------------------
Place model:
public function categories()
{
return $this->belongsToMany('App\Category','category_places','place_id','category_id');
}
in my Item controller
public function create()
{
$activeMenu = 'placetypes';
$placetype = new PlaceType();
return view('Admin.placeTypes.create',['placetype'=>$placetype,'activeMenu'=>$activeMenu]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(PlaceTypeFormRequest $request)
{
// PlaceType::create([
// 'name'=>$request->input('name'),
// 'icon'=>$request->input('icon'),
// 'status'=>$request->input('status'),
// ]);
if($request->hasFile('image_name'))
{
$filenameWithExt = $request->file('image_name')->getClientOriginalName();
$filename = pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension = $request->file('image_name')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('image_name')->storeAs('public/photos',$fileNameToStore);
}else
{
$fileNameToStore = 'No-Image-Available.png';
}
$pt = new PlaceType();
$pt->name = $request->input('name');
$pt->status = $request->input('status');
$pt->icon = $fileNameToStore;
$pt->save();
return redirect('/placeTypes')->with('succes','تمت إضافة قسم المحل بنجاح');
}
in ruoutes web.php
Route::resource('places','Admin\PlaceController');
....
in my create.blade.php view
<div class="form-group" >
<label class="text-primary" dir="rtl" for="exampleFormControlSelect1">{{trans('admin.theplace')}}</label>
<select class="form-control" name="place" data-style="btn btn-link" id="exampleFormControlSelect1">
#foreach($places as $pt)
<option value="{{$pt->id}}" {{ ($pt->name)? "selected" : '' }} >{{$pt->name}}</option>
#endforeach
</select>
</div>
<div class="form-group" >
<label class="text-primary" dir="rtl" for="exampleFormControlSelect1">{{trans('admin.itemCats')}}</label>
<select class="form-control" name="itemcat" id="category" data-style="btn btn-link" id="exampleFormControlSelect1">
#foreach($categories as $cat)
<option value="{{ $cat->id }}" {{ (isset($cat->name))? "selected" : '' }} >{{$cat->name}}</option>
#endforeach
</select>
</div>
Jquery code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function dropdown(msg){
var place=msg;
$.ajax({
url: 'getcategory/'+place,
type: 'get',
dataType: 'json',
success: function(response){
$("#category").empty();
var len = 0;
if(response['data'] != null){
len = response['data'].length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var id = response['data'][i].id;
var name = response['data'][i].name;
var option = "<option value='"+name+"'>"+name+"</option>";
$("#category").append(option);
}
}
}
});
}
</script>
use onchange .try this
<div class="form-group" >
<label class="text-primary" dir="rtl" for="exampleFormControlSelect1">{{trans('admin.theplace')}}</label>
<select class="form-control" name="place" data-style="btn btn-link" id="exampleFormControlSelect1">
#foreach($places as $pt)
<option value="{{$pt->id}}" {{ ($pt->name)? "selected" : '' }} >{{$pt->name}} onchange="dropdown('{{$p->id}}')"</option>
#endforeach
</select>
</div>
<div class="form-group" >
<label class="text-primary" dir="rtl" for="exampleFormControlSelect1">{{trans('admin.itemCats')}}</label>
<select class="form-control" name="itemcat" id="category" data-style="btn btn-link" id="exampleFormControlSelect1">
#foreach($categories as $cat)
<option value="{{ $cat->id }}" {{ (isset($cat->name))? "selected" : '' }} >{{$cat->name}}</option>
#endforeach
</select>
</div>
I have to do this often, and this my way of doing it
HTML/Blade
<select name="select_name" id="select1" class="form-control">
<option value="">choose</option
#foreach($models as $model)
<option value="{{ $model->id }}">{{ $model->attribute }}</option>
#endforeach
</select>
<select name="select_name" id="select2" class="form-control">
<option value="">choose select 1 first</option>
</select>
And this is jQuery
$("#select1").change(function(e){
var model = e.target.value;
$.get("/api/your-route?input="+model, function(data){
$("#select2").empty();
$("#select2").append("<option value=''>choose</option>");
$.each(data, function(index, obj){
$("#select2").append("<option value='model.id'>model.attribute</option>");
});
});
});
Laravel
public function func_name(Request $request){
//if you work with Laravel 5.8 or older, you could you the input facade
$childern = Child::where('parent_id', $request->input('parent'))->get();
return response()->json($childern, 200);
// if you want to use a resource, that's even better
}
It always worked for me like a charm, and since i get values from api every time the parent changes, I don't have to worry about someone playing with values from the inspector
Instead of making a GET request to getcategory/{place} try to make the request to getcategory and pass the place id as a perimeter. You also need to have the change method on the place dropdown.
jQuery
$('#exampleFormControlSelect1').change(function() {
$.ajax({
url: '/getcategory',
type: 'GET',
data: {id: $('#exampleFormControlSelect1').val()}
}).done(function(response){
//what you want to do with your response//
});
});
Controller
public function getCategory(Request $request)
{
return Place::where('id', $request->id)->categories()->pivot->category_id->get();
}
From here your response should be a collection of all the category_ids in the pivot table for the place that you pass.