У меня есть форма ниже с 4 полями со списком «Metier = профессия» «tache = task» «tacrification = pricing» и «technicien = technician», а имя техника находится в таблице user Dynamique combobox return 'undefined' name variable when i выберите техник, но когда я делаю идентификатор на скрипте, он работает
контроллер вмешательства
<?php
namespace App\Http\Controllers;
use App\zoneintervention;
use App\technicien;
use App\Intervention;
use App\metier;
use App\tache;
use App\client;
use App\user;
use App\adresse;
use App\Tarification;
use App\tarificationtache;
use Illuminate\Http\Request;
use App\Http\Requests\InterventionRequest;
use DB;
class InterventionController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$Listintervention=Intervention::with(['technicien','client',
'tarificationtache'])->get();
return view('intervention.index',['interventions'=>$Listintervention]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$user= user::orderBy('id', 'asc')->get();
$client = client::orderBy('id', 'asc')->get();
$metiers = metier::orderBy('id', 'asc')->get();
$technicien = Technicien::orderBy('id', 'desc')->get();
$tarifications = tarificationtache::orderBy('id', 'desc')->get();
return view('intervention.create')->with('technicien', $technicien)-
>with('client',$client)->with('metiers',$metiers)-
>with('tarifications',$tarifications);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(InterventionRequest $request)
{
$intervention = new Intervention();
$intervention ->description =$request->input('description');
$intervention ->duree_prevu =$request->input('duree_prevu');
if ($request->has('statut')){
$intervention->statut = $request->input('statut');
}else{
$intervention->statut = 0;
}
$intervention ->technicien_id = $request->input('technicien_id');
$intervention ->client_id = $request->input('client_id');
$intervention ->tarification_id = $request->tarificationtache_id;
$intervention->save();
return redirect('intervention');
}
public function prodfunct(){
$technicien=technicien::all();//get data from table
return redirect('intervention',compact('technicien'));//sent data to
view
}
public function findlibelle_metier(Request $request){
$metier=metier::all();//get data from table
return redirect('intervention',compact('metier'));//sent data to view
}
public function findProductName(Request $request){
//if our chosen id and products table prod_cat_id col match the get
first 100 data
//$request->id here is the id of our chosen option id
$data=tache::select('libelle_tache','id')->where('metier_id',$request-
>id)->take(100)->get();
return response()->json($data);//then sent this data to ajax success
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show( $id)
{
$intervention=Intervention::find($id);
$technicien = $intervention->technicien;
$tarificationtache = tarificationtache::orderBy('id', 'desc')->get();
return view('intervention.show',['intervention'=>$intervention])-
>with('technicien',$technicien)->with('tarificationtache',
$tarificationtache);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$intervention=Intervention::find($id);
return view('intervention.edit',['intervention'=>$intervention]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(InterventionRequest $request, $id)
{
$intervention=Intervention::find($id);
$intervention ->date_intervention =$request->input('date_intervention');
$intervention ->description =$request->input('description');
$intervention ->duree_prevu =$request->input('duree_prevu');
$intervention ->statut =$request->has('statut');
$intervention->save();
return redirect('intervention');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$intervention =intervention::find($id);
$intervention->delete();
return redirect('intervention');
}
}
create.blade.php
@extends('Layouts/app')
@extends('Layouts/master')
@section('content')
<!-- jQuery -->
<script
src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script type = "text/javascript">
var getTachesByMetierUrl = "{{url('/tachesbymetier')}}";
var getAdresseByClientUrl = "{{url('/adressebyclient')}}";
var getTarificationsByTacheUrl = "{{url('/tarificationsbytache')}}";
var getTechniciensByTarificationtacheUrl = "
{{url('/techniciensbytarificationtache')}}";
function getAdresseByClient(val) {
if (val.length>0) {
var client_id = val;
$.get(getAdresseByClientUrl+'/'+client_id,function(res) {
var html = '<option value = "">-Select-</option>' ;
$.each(res.adresses,function(index,item) {
html+='<option
value = "'+item.id+'">'+item.code_postal+'</option>';
});
$('#adresses').html(html);
});
}
}
function getTachesByMetier(val) {
if (val.length>0) {
var metier_id = val;
$.get(getTachesByMetierUrl+'/'+metier_id,function(res) {
var html = '<option value = "">-Select-</option>' ;
$.each(res.taches,function(index,item) {
html+='<option
value = "'+item.id+'">'+item.libelle_tache+'</option>';
});
$('#taches').html(html);
});
}
}
function getTechniciensByTache(val) {
if (val.length>0) {
var tache_id = val;
$.get(getTechniciensByTacheUrl+'/'+tarificationtache_id,function(res) {
var html = '<option value = "">-Select-</option>' ;
$.each(res.techniciens,function(index,item) {
html+='<option
value = "'+item.id+'">'+item.id.nom+'</option>';
});
$('#techniciens').html(html);
});
}
}
function getTarificationsByTache(val) {
if (val.length>0) {
var tache_id = val;
$.get(getTarificationsByTacheUrl+'/'+tache_id,function(res) {
var html = '<option value = "">-Select-</option>' ;
$.each(res.tarifications,function(index,item) {
html+='<option
value = "'+item.id+'">'+item.tarif+'</option>';
});
$('#tarifications').html(html);
});
}
}
function getTechniciensByTarificationtache(val) {
if (val.length>0) {
var tarificationtache_id = val;
$.get(getTechniciensByTarificationtacheUrl+'/'+tarificationtache_id,
function(res ) {
var html = '<option value = "">-Select-</option>' ;
$.each(res.techniciens,function(index,item) {
html+='<option
value = "'+item.id+'">'+item.id.nom+'</option>';
});
$('#techniciens').html(html);
});
}
}
</script>
@if (count($errors))
<div class = "alert alert-danger" role = "alert">
<ul>
@foreach($errors ->all() as $message)
<li>{{$message}}</li>
@endforeach
</ul>
</div>
@endif
<div class = "container">
<div class = "row"></div>
<div class = "col-md-10">
<h1>Ajout Intervention</h1>
<form action = " {{url ('intervention') }}" method = "post">
{{csrf_field()}}
<div class = "form-group">
<label for = "client">Client</label>
<select onchange = "getAdresseByClient(this.value)"
name = "client_id" id = "client" class = "form-control">
<option value = "">-Select-</option>
@foreach($client as $t)
<option value = "{{$t->id }}">
{{$t->user->nom}}
</option>
@endforeach
</select>
</div>
<div class = "form-group">
<label for = "">date et heure </label>
<input class = "form-control" type = "datetime-local" name
= "duree_prevu" value = "{{old('duree_prevu')}}">
</div>
<div class = "form-group">
<label for = "">description</label>
<input type = "text" name = "description" class = "form-
control"value = "{{old('description')}}">
</div>
<div class = "form-group">
<div class = "col-md-12">
<div class = "col-md-4">
<label>Metier: </label>
<select onchange = "getTachesByMetier(this.value)"
style = "width: 200px" class = "productm form-control" id = "metiers">
<option value = "">-Select-</option>
@foreach($metiers as $t)
<option value = "{{$t->id }}">
{{$t->libelle_metier}}
</option>
@endforeach
</select>
</div>
<div class = "col-md-4">
<label>tache: </label>
<select onchange = "getTarificationsByTache(this.value)"
style = "width: 200px" class = "productname form-control" name = "tache"
id = "taches">
<option value = "">-Select-</option>
</select>
</div>
<div class = "col-md-4">
<label>tarification: </label>
<select
onchange = "getTechniciensByTarificationtache(this.value)" style = "width:
200px"
class = "productname form-control" name = "tarificationtache_id"
id = "tarifications">
<option value = "">-Select-</option>
</select>
</div>
<div class = "col-md-4">
<label>technicien: </label>
<select style = "width: 200px" class = "productname
form-control" name = "technicien_id" id = "technicien">
<option value = "">-Select-</option>
</select>
</div>
</div>
<div class = "form-group">
<div class = "form-group">
<label for = "">statut : </label>
<input type = "checkbox" name = "statut" value = "1" required
autofocus>
</div>
<div class = "form-group">
<label for = "">payement</label>
<input type = "checkbox" name = "payement" value = "">
</div>
<div class = "form-group">
<input type = "submit" value = "enregistrer" class = "form-
control btn btn-primary">
</div>
</div>
</div>
</div>
<link
href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
rel = "stylesheet">
<link href = "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datepicker/1.5.0/css/bootstrap-datepicker.css" rel = "stylesheet">
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datepicker/1.5.0/js/bootstrap-datepicker.js"></script>
@endsection
стол техник
Schema::create('techniciens', function (Blueprint $table) {
$table->increments('id');
$table->boolean('actif')->default(1);
$table->float('moyenne_avis')->nullable();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->datetime('deleted_at')->nullable();
$table->timestamps();
});
*



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вместо:
html+='<option value = "'+item.id+'">'+item.id.nom+'</option>';
тебе нужно:
html+='<option value = "'+item.id+'">'+item.user.nom+'</option>';
И измените это:
public function getTechniciensByTarificationtache($tarificationtache_id)
{
$t = tarificationtache::with('techniciens.user')->find($tarificationtache_id);
return response()->json(['techniciens' => $t->techniciens]);
}
@ chagou2704 вы изменили код в двух местах, но он все еще не работает?
@ yrv16 да, это не работает для более подробного объяснения У меня есть 2 таблицы tarificationtache и technicien с отношением mony к mony, а technicien наследует 'nom' от пользователя таблицы
@ chagou2704 Какой метод контроллера вызывается для запроса ajax в getTechniciensByTarificationtache?
@ yrv16 да getTechniciensByTarificationtache, и я вызвал эту функцию на techniciencontrooler с помощью этой публичной функции кода getTechniciensByTarificationtache ($ tarificationtache_id) {$ t = tarificationtache :: find ($ tarificationtache_id); return response () -> json (['techniciens' => $ t-> techniciens]); }
@ chagou2704 Я спрашиваю, какой метод обрабатывает этот URL getTechniciensByTarificationtacheUrl. Покажи мне метод контроллера для этого URL.
@ chagou2704 Можете ли вы показать структуру таблицы техников?
@ yrv16 я добавил в свой вопрос таблицу technciens
@ chagou2704 Имеете ли вы какое-либо отношение к технической модели получения пользовательских данных? Потому что вам нужен nom, и он есть в таблице пользователей. Итак, вам нужно это отношение, чтобы получить свойство nom.
@ yrv16 причин у меня есть эта публичная функция user () {return $ this-> ownTo (User :: class); }
@ yrv16 ТЕПЕРЬ НИЧЕГО НЕ ОТОБРАЖАЕТСЯ В ТЕХНИЧЕСКОЙ ОБЛАСТИ
@ chagou2704 Вы можете console.info(res.techniciens) и показать мне результат?
@ yrv16 я не знаю, как это сделать, не могли бы вы объяснить, пожалуйста
@ chagou2704 Добавьте console.info(res.techniciens) после var html = '<option value = "">-Select-</option>' ; и откройте devTools (F12), затем перейдите на вкладку консоли, и там вы увидите структуру вашего объекта.
@ yrv 16 когда я выбираю тарификацию, у меня ошибка
GET локальный / проект / общедоступный / techniciensbytarificationtache / 4 500 (внутренняя ошибка сервера) send @ jquery.min.js: 4 ajax @ jquery.min.js: 4 r. (Анонимная функция) @ jquery.min.js: 4 getTechniciensByTarificationtache @ create: 204 onchange @ create: 298 ListPicker._handleMouseUp
@ chagou2704 localhost/projet/public/techniciensbytarificationtache/4 поместите это в URL-адрес браузера и сделайте снимок экрана для страницы результатов, затем прикрепите его сюда, чтобы увидеть ошибку.
@ chagou2704 Я обновил ответ
@ yrv 16 большое спасибо у меня есть еще один вопрос, если у вас есть время, вы можете мне помочь
@ chagou2704 Создать новую тему для нового вопроса.
@ yrv16 stackoverflow.com/questions/50466418/…
Спасибо за вашу помощь. Я работал с "getTechniciensByTarificationtache" той же проблемой, когда пытался переосмыслить