I need to find the data coresponding to a specific id, i keep getting this error, i tried dump the id value and it shows NULL
, no idea why, here is code :
Controller :
function fetchdata(Request $request)
{
$id = $request->get('ID');
$req = Demo::find($id);
$output = array(
'reponse' => $req->reponse,
);
echo json_encode($output);
}
View :
$(document).on('click', '.req_reponse', function(){
var id = $(this).attr("ID");
$('#form_output').html('');
$.ajax({
url:"{{route('admin.fetchdata')}}",
method:'get',
data:{id:id},
dataType:'json',
success:function(data)
{
$('#reponse').val(data.reponse);
$('#ID').val(id);
$('#studentModal').modal('show');
}
})
});
Error :
'reponse' => $req->reponse,
"Trying to get property of non-object"
Getting error because there is no key like reponse in $req variable.
I think this should work fine:
$id = $request->ID;
$demo = Demo::find($id);
if (empty($demo)) {
exit(json_encode(['message' => "not found"])); // Or any thing you want to return if record not found corresponding to given id.
}
$output = array(
'reponse' => $demo->reponse,
);
echo json_encode($output);
exit;
Eloquent doesn't provide such a key response
. Please try the below script.
function fetchdata(Request $request)
{
$id = $request->get('ID');
$req = Demo::find($id);
$output = array(
'reponse' => $req->your_column_name,
);
echo json_encode($output);
exit;
}