Я делаю простое приложение для чата с API и Ajax;проблема заключается в том, что когда я делаю запрос Ajax и сохраняю в своей БД разговор в чате и сообщение, если разговор существует, просто сохраните сообщение.Но когда я сохраняю сообщение, запрос не принимает идентификатор, а когда я сохраняю чат, беру его.
Laravel
public function storeMsj(Request $req)
{
$existChat = $this->existsChat($req->id);
if ($existChat == 0) {
Chat::create([
'user' => $req->id,//here take the request
'read' => 0,
]);
Message::create([
'message_content' => $req->msj,
'from' => $req->id,//here not take the request
'to' => 1,
]);
} else {
Message::create([
'message_content' => $req->msj,
'from' => $req->id,
'to' => 1,
]);
}
return Response::json($req->id);//the response show correctly the request
}
JS
function storeMsj(){
let msj = document.querySelector('.msg').value;
let id = idUser.firstElementChild.innerHTML;
fetch('/api/storeMsj',{
method: 'POST',
headers:{
'Accept': 'application/json, text/plain, */*',
'Content-type': 'aplication/json'
},
body: JSON.stringify({
msj: msj,
id: id
}),
})
.then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}