Fill select box from other vuejs laravel axios - php

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.

Related

How to display database details immediately when user choose any dropdown value in laravel using ajax?

I want to display details from the selected dropdown. All the details are from the database. The problem is, the price did not display when user choose 1 dropdown value. Which part did I missed? Here is my code:
Route:
Route::get('/prodview', [OrderController::class, 'prodfunct']);
Route::get('/findPrice', [OrderController::class, 'findPrice']);
Controller:
public function prodfunct()
{
$prod=DB::all();//get data from table
return view('orders.order',compact('prod'));//sent data to view
}
public function findPrice(Request $request){
//it will get price if its id match with product id
$p=DB::select('select price from pastas')->where('id',$request->id)->first();
return response()->json($p);
}
View:
<span>
<x-label for="pastaingredient" :value="__('Pasta Ingredient: ')" />
<x-input id="pastaingredient" style="font-size:14px;" class="pasta_ingredient" type="text" name="pastaingredient" value="{{ old('pasta_ingredient') }}" disabled />
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change', '.pastas', function()
{
var ingredient = $(this).find("option:selected").data("ingredient");
$('.pasta_ingredient').val(ingredient);
});
});
</script>
Other way to achieve this would be storing price value as data-attribute and then whenever user select any value from select-box you can simply use $(this).find("option:selected").data("price") to get value from options .
So , you just need to add data-price="{{ $pizzaitem->price }}" to your options i.e :
<option #if(old('pastas') == $pizzaitem->name) selected #endif value="{{ $pizzaitem->name }}" data-price="{{ $pizzaitem->price }}">{{ $pizzaitem->name }}</option>
Then , your jquery code will be like below :
$(document).on('change', '.pastas', function() {
var price = $(this).find("option:selected").data("price");
$('.prod_price').val(price);
});
The function var a=$(this).parent(); return the immediate parent of this. In this case, a is this div:
<div>
<x-label for="pastas" :value="__('Choose pastas:')" />
<select name="pastas" id="pastas" class="pastas">
<option #if(!old('pastas')) selected #endif disabled>Please choose</option>
#foreach ($pastainfo as $pizzaitem)
<option #if(old('pastas') == $pizzaitem->name) selected #endif value="{{ $pizzaitem->name }}">{{ $pizzaitem->name }}</option>
#endforeach
</select>
</div>
so that at this line a.find('.prod_price').val(data.price); JQuery only find prod_price in the a div and can not see it there leading this error.

Laravel: Passing selected values to route function from dropdown selection

I have a dropdown list that I want to be able to select a value and modify a value in the MYSQL table by calling a function on change.
The drop list is created with:
<td>
{{-- {{ $ticket->priority}} --}}
<div class="form-group{{ $errors->has('priority') ? 'has-error': '' }}">
<div class="col-md-6">
<select id="priority" type="" class="form-control" name="priority"
onchange="{{ url('admin/updatePriority/',['ticket_id' => $ticket->ticket_id, 'priority'=> value ] )}}">
<option value="">{{ $ticket->priority}}</option>
<option value="Low">Low</option>
<option value="Moderate">Moderate</option>
<option value="High">High</option>
</select>
</div>
</div>
</td>
The function in the Routes is:
Route::group(['prefix' => 'admin', 'middleware' => 'admin'], function () {
Route::get('tickets', 'TicketsController#index');
Route::post('close_ticket/{ticket_id}', 'TicketsController#close');
Route::post('updatePriority/{ticket_id}/{priority}', 'TicketsController#updatePriority');
});
The code for the function is:
public function updatePriority($ticket_id, $priority)
{
$ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail();
$ticket->priority = $priority;
$ticket->save();
}
When I make a selection from the dropdown box, the onchange function is not triggered, so the value remains unchanged in the table.
Can anyone point me in the right direction on this?
HTML event listeners expect Javascript code or function calls, a URL is not valid in such context
Here's what you can do
<td>
<div class="form-group{{$errors->has('priority') ? 'has-error': '' }}">
<div class="col-md-6">
<select id="priority" type="" class="form-control" name="priority" onchange="change({{ $ticket->ticket_id }}, this.value)">
<option value="">{{ $ticket->priority}}</option>
<option value="Low">Low</option>
<option value="Moderate">Moderate</option>
<option value="High">High</option>
</select>
</div>
</div>
</td>
<script>
function change(ticket_id, priority) {
const response = fetch('/admin/updatePriority/' + ticket_id + '/' + priority, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": document.head.querySelector('meta[name="csrf-token"]')
},
method: "post",
});
console.log(JSON.stringify(response));
}
</script>
This is using the native Ajax fetch API to perform the request to the URI with the dynamically changed value of the select element as parameter
Note that you still need to deal with CSRF header and to properly call the parameters in the controller from the request object
Hope this helps

Laravel Passing Variables to Multiple Select Drop Down Array to string conversion Error

I am trying to push multiple selections from a drop down of specialties being displayed from my $specialties variable in an #foreach in a laravel application. I am able to capture 1 id and push it to the database, but multiple selections do not work. It only pushes one ID to the database. When I try name="specialties[]" as below I get error: Array to string conversion. How do I push my selection into an array using eloquent?
My form View:
<div class="container">
{{ csrf_field() }}
<strong>Select Specialty:</strong>
<select id="multiple-checkboxes2" multiple="multiple" name="specialties[]" value="specialties">
#if($specialties)
#foreach($specialties as $specialty)
<option value=" {{$specialty->id}} ">{{$specialty->name}}</option>
#endforeach
#endif
</div>
</select>
{!! Form::close() !!}
<script type="text/javascript">
$(document).ready(function() {
$('#multiple-checkboxes2').multiselect();
});
Client Store Controller
public function store(Request $request)
{
//
Client::create([
'specialties' => $request->specialties,
] );
return redirect('/accounts');
}
Client display controller
public function display($id)
{
$specialties=Specialty::select( 'name', 'id')->orderBy('name', 'asc')->get('id');
return view('accounts/display', compact('accounts', 'specialties', )->withAccount($accounts);
}
}
try to use array
<select id="multiple-checkboxes2" multiple="multiple" name="specialties[]">
#if($specialties)
#foreach($specialties as $specialty)
<option value= "{{ $specialty->id }}">{{$specialty->name}}</option>
#endforeach
#endif
</select>

Laravel ErrorException, Performing Multiple dynamic drop down

I have four tables:
asset_category table(columns 'asset_category_id', 'category'), an assets table(columns 'asset_id','asset_category_id','manufacturer_id', 'department_id'),
manufacturers table (columns manufacturers_id, manufacturer) and departments table (columns department_id, department). The asset table columns are linked with the other three table. I'm performing a dynamic drop down in the form to insert into the asset table
Asset.blade.php
<form action="{{url('/insertAsset')}}" method="POST" edata-parsley-validate novalidate>
{{ csrf_field() }}
<div class="form-group">
<label for="userName">Asset ID*</label>
<input type="text" name="asset_id" parsley-trigger="change" required placeholder="Asset ID" class="form-control" id="userName" disabled>
</div>
<div class="form-group">
<label for="userName">Asset Category ID*</label>
<select name="asset_category_id" parsley-trigger="change" required placeholder="Asset Category ID" class="form-control">
<option>Select an Asset Category</option>
#foreach( $asset_categories as $asset_category )
<option value=" {{$asset_category->asset_category_id}}"> {{ $asset_category->category }} </option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="userName">Asset Manufacture ID*</label>
<select name="manufacturer_id" parsley-trigger="change" required class="form-control">
<option>Select a Manufacturer</option>
#foreach( $manufacturers as $manufacturer )
<option value=" {{$manufacturer->manufacturer_id}}"> {{ $manufacturer->manufacturer }} </option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="userName">Department ID*</label>
<select name="department_id" parsley-trigger="change" required placeholder="Department ID" class="form-control" >
<option>Select a Department</option>
#foreach( $departments as $department )
<option value=" {{$department->department_id}}"> {{ $department->department }} </option>
#endforeach
</select>
</div>
<div class="form-group text-right m-b-0">
<button class="btn btn-primary waves-effect waves-light" type="submit">
Submit
</button>
</div>
AssetController
<?php
namespace App\Http\Controllers;
use App\Asset;
use App\Asset_category;
use App\Manufacturer;
use App\Department;
use Illuminate\Http\Request;
class AssetController extends Controller
{
public function asset_category(){
$asset_categories = Asset_category::all();
return view('asset', ['asset_categories' => $asset_categories]);
}
public function manufacturer(){
$manufacturers = Manufacturer::all();
return view('asset', ['manufacturers' => $manufacturers]);
}
public function department(){
$departments = Department::all();
return view('asset', ['departments' => $departments]);
}
}
Web.php
<?php
Route::get('/asset', function (){
return view('asset');
} );
Route::get('/asset', 'AssetController#asset_category');
Route::get('/asset', 'AssetController#department');
Route::get('/asset', 'AssetController#manufacturer');
/*POST */
Route::post('/insertAsset', 'AssetController#add');
When run the application, i get an ErrorException which states:
Undefined variable: asset_categories (View: C:\xampp\htdocs\laravel_app\resources\views\asset.blade.php).
After thorough testing i find out that, just one drop down displays because the laravel routes only one variable from one function among the 3 functions in the web.php and the other two variable from the other functions are not sent to the asset.blade.php. So now i want a way to route the other variables to the asset.blade.php. Please help if you understand it. Thanks in advance.
The first thing is that Laravel will only match the first route with the specific ID and specific type. In these case will only find the first route GET /asset.
To do what I undestand you want. You need to create only one method, that will return the three variables to the view
public function asset(){
$asset_categories = Asset_category::all();
$manufacturers = Manufacturer::all();
$departments = Department::all();
return view('asset', ['asset_categories' => $asset_categories,
'manufacturers' => $manufacturers, 'departments' => $departments]);
}
And only one route
Route::get('/asset', 'AssetController#asset');

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