Как из таблицы вытащить элемент по 2 параметрам и изменить laravel
Каким образом мне вытащить элемент из таблицы в БД по 2 параметрам и изменить например его текст. Вот ,что пробовал:
public function ajaxComments(Request $request)
{
// записываем наёденную строку из БД в переменную
$itComment = Comments::where(['userId':$request->userId,
'companyId':$request->companyId,
])
// проверяем, если данные в ней есть, то перезаписываем (вообще не уверен в коде ниже т.к не знаю как обновить данные в таблице)
if ($itComment){
$itComment= $request->name;
$itComment= $request->INN;
$itComment= $request->informC;
$itComment= $request->nameDirec;
$itComment= $request->addressC;
$itComment= $request->phoneC;
$itComment->save();
return redirect(route('home'));
}else{
//если не нашли то создаём новый комментарий
$comments = new Comments();
$comments->idUser = $request->userId;
$comments->idCompany = $request->companyId;
$comments->comName = $request->name;
$comments->comINN = $request->INN;
$comments->comInform = $request->informC;
$comments->comNameDirec = $request->nameDirec;
$comments->comAddress = $request->addressC;
$comments->comPhone = $request->phoneC;
$comments->save();
return redirect(route('home'));
}
}
Ответы (2 шт):
Автор решения: jackalxtxff
→ Ссылка
все гораздо проще) Просто используй 2 раза where. Cмотри:
$itComment = Comments::where('userId', $request->userId)->where('companyId', $request->companyId)->get();
Автор решения: Павел Кулик
→ Ссылка
public function ajaxComments(Request $request)
{
$comment = Comment::where([
'userId' => $request->userId,
'companyId' => $request->companyId,
])->firstOrCreate();
$comment= $request->name;
$comment= $request->INN;
$comment= $request->informC;
$comment= $request->nameDirec;
$comment= $request->addressC;
$comment= $request->phoneC;
$comment->save();
return redirect(route('home'));
}
Отредактировал немного ваш код. Не забудьте $userId и $companyId добавить в массив $fillable