I have a problem with my registration, I am trying to capture the id_student that I just registered, but the problem is that I am sending my student registration + registration of a schedule, so they are done at the same time and I cannot capture the id of the registered student . The classes of the schedule must have the id of the student to whom I am assigning said schedule.
the student is sent through a post form with their respective route and the schedule was sent through ajax and also with their respective route. At the moment of sending the ajax, I activate the submit of the student form so that when the "Save" button is pressed, the submit and the json of the schedule are sent
This is my student form
<form id="alumno-frm" name="alumno-frm" class="form-horizontal" action="{{ route('alumno.store') }}" method="post" enctype="multipart/form-data">
This is the ajax in which I send the json that I get from the fnGetData of my schedule datatable and activate the student submit
$.ajax({
url:"{{ route('alumno.horario') }}",
type: 'POST',
dataType:'json',
contentType: 'json',
data: JSON.stringify(p),
contentType: 'application/json; charset=utf-8',
success : function(){
$('#alumno-frm').submit(); // ENVIO FORMULARIO DE ALUMNO MEDIANTE SU RUTA
},
error: function(){
Toast.fire({
type: 'error',
title: 'Ha ocurrido un problema con el registro de horario práctico'
});
}
});
This is the student function in the controller
public function store(Request $request){ // STORE
$alumno = alumnoModel::updateOrCreate(['id_alumno' => $request->id_alumno],
[
'rut' => $request->rut,
'nombre' => $request->nombre,
'apellidos' => $request->apellidos,
'correo' => $request->correo,
'clave' => $request->clave,
'telefono' => $request->telefono,
'id_curso' => $request->curso,
'id_licencia' => $request->licencia
]
);
$message= array(
'message' => 'Alumno ha sido agregado con exito',
'type' => 'success'
);
return redirect()->back()->with($message);
}
and this is the function of the schedule in which it is seen that it tries to do it by obtaining the last record and adding 1 to it, but the problem is that since it does not have subsequent records it gives me an error and I know that it is wrong to do it that way.
public function storeHorario(Request $request){ // GUARDAR HORARIO
$id_alumno = alumnoModel::orderby('id_alumno','desc')->select('id_alumno')->first(); // intento 1
$data = json_decode($request->getContent());
foreach($data as $array_data) {
$dato2 = $array_data['0'];
$dato3 = $array_data['1'];
$dato4 = $array_data['2'];
$dato5 = 'practica';
$dato6 = $array_data['3'];
$dato7 = $array_data['7'];
$dato8 = $array_data['8'];
$dato9 = $array_data['9'];
$dato10 = $array_data['10'];
horarioModel::updateOrCreate(
['id_horario' => $dato9?: NULL],
[
'clase' => $dato2,
'fecha' => $dato3,
'hora' => $dato4,
'tipo' => $dato5,
'minutos_bloque' => $dato6,
'id_profesor' => $dato7,
'id_vehiculo' => $dato8,
'id_curso' => $dato10,
'id_alumno' => $id_alumno->id_alumno+1 // sumo 1 al ultimo registro de alumno
]
);
}
return json_encode($data);
}
I had thought of something like a timeout to wait for the student to register first and then run the schedule function to capture the last registration student_id, but I searched and found nothing like that.
I thank you in advance for the help.
Edition
Swal.fire({
title: 'Confirmacion!',
text: "Se creara el alumno y se le asignara al curso seleccionado",
showCancelButton: true,
confirmButtonColor: '#28A645',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, registrar alumno',
cancelButtonText: 'No, volver'
}).then((result) => {
if (result.value) {
// captura el evento submit del formulario y previene su acción por defecto
$('#alumno-frm').on('submit', function(e) {
e.preventDefault();
// crea un array con los datos del formulario
let form = document.forms["alumno-frm"];
let fd = new FormData(form);
let alumno = {};
for (let [key, prop] of fd) {
alumno[key] = prop;
}
// crea un array con los datos de la tabla
let horarios = $("#tablaAgregados").dataTable().fnGetData();
// agrega ambos a la data que envías con ajax, convirtiédolos a json
$.ajax({
url:"https://jsonplaceholder.typicode.com/posts", // reemplaza esta url por la ruta que corresponda para que llegue a la función store del Controlador
type: 'POST',
data: JSON.stringify({
alumno: alumno,
horarios: horarios
}),
contentType: 'application/json; charset=utf-8',
success : function(response){
console.log(response)
},
error: function(response){
console.log(response)
}
});
});
}
})
When pressing the btnCrear (save) the confirmation sweetAlert is executed, once I click "yes" it does nothing Just in case I will leave a pastebin with the complete button so that it is better understood ( https://pastebin.com/ iDhnyvmr ), regarding the controllers, the 2 functions (store and storeHorario) are exactly as indicated by @porloscerros Ψ
2nd way https://pastebin.com/GBdTiXES I made this way while waiting for some response, it also works without problems, but I recommend using the solution given by @porloscerros Ψ
Something that occurs to me is that you can send all the data, the one from the student form and the data from the table in the same call.
Then you handle it in your controller to register them in the DB.
I leave you some comments in the code so you have the idea.
In your jscript:
In the controller, receive the data in the public function where you register the student and then you pass the schedule data to the function that registers the schedule data:
I had a similar problem and the way I solved it was by forcing the ajax requests to be synchronous (I have to admit that it hasn't always worked for me to do that), but maybe I can help you. To make the requests synchronous you can do it as follows:
Be careful using these synchronous requests as they could crash your application if you are not careful as a synchronous request blocks the application until it is done