【发布时间】:2021-03-05 01:27:23
【问题描述】:
请帮助我,我在 Laravel 中有一个 AJAX 搜索表单。它在数据库“患者”中搜索,他们在其中有一行“已分配”,他们被分配给用户的 ID。用户通过 AJAX 搜索表单进行搜索,以找到患者。我希望用户能够搜索并且结果只显示分配给他的患者,我不希望用户能够搜索和查看数据库中的所有患者。这是我到目前为止尝试过的,但它并没有真正起作用,请给我一些想法:
PatientController.php
function searchPatients(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
if(Auth::user() -> role == 'user'){
$data = DB::table('patients')
->where('assigned', auth()->user()->id)
->where('name', 'like', '%'.$query.'%')
->orWhere('city', 'like', '%'.$query.'%')
->orWhere('country', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->get();
}
if(Auth::user() -> role == 'admin' || Auth::user() -> role == 'photostudio'){
$data = DB::table('patients')
->where('name', 'like', '%'.$query.'%')
->orWhere('city', 'like', '%'.$query.'%')
->orWhere('country', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->get();
}
}
else
{
/*$data = DB::table('patients')
->orderBy('id', 'desc')
->get();*/
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<div class="col-md-12 text-center offset-md-9">
<a href='.route("admin.patient", ["id" => $row->id]) .' style="text-decoration:none; color:black;">
<div class="card-mt-3">
<div id="records-patients" class="records-patients">
<div class="card-header">
Пациент: '. $row -> name. '
</div>
<div class="card-body">
<h3>Телефон:'.$row -> phone.'</h3>
<h3>Имейл: '. $row-> email.'</h3>
</div>
</div>
</div>
</a>
</div>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">Nothing found, please try again</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
AJAX 搜索表单和前端
<script>
$(document).ready(function(){
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('admin.patients.search') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
if(query !== ''){
$('#patientsshow').html(data.table_data);
$('#total_records').text(data.total_data);
}
}
})
}
$(document).on('keyup', '#search-patients', function(){
var query = $(this).val();
if(query !== ''){
fetch_customer_data(query);
}
});
});
</script>
<div class="row">
<div id="patientsshow">
</div>
</div>
【问题讨论】: