0

i want to search data based nama_kegiatan or tanggal_kegiatan where these two name form my table field, this code from my controller :

public function search(Request $request){
$cari = $request->search;
$caritanggal = date($request->datekeg);
$infokeg = Infokeg::where(function ($query) use ($cari) {
    $query->where('nama_kegiatan','like',"%$cari%")->get();
})->orWhere(function($query) use ($caritanggal) {
    $query->where('tanggal_kegiatan', $caritanggal)->get();;   
})->paginate(10);

return view('infokeg/infokeg', ['infokeg' => $infokeg]);
}

when i am using like on nama_kegiatan, tanggal_kegiatan didnt work and just display all data, but when i delete like from nama_kegiatan, its work, but i cant search nama_kegiatan using like, so how to solve it ?

Fariza
  • 33
  • 4

3 Answers3

2

Maybe you can try to get() all the result after the query? Somethings like

$infokeg = Infokeg::where('name_kegiatan','LIKE','%'.$cari.'%')->orWhere('tanggal_kegiatan',$caritanggal)->get();

IMO the get() and paginate() cannot be use at the same time if I have not get it wrong. If you need to paginate after all the result, you can do create Paginator manually. Maybe this link can help you. Hope this will help you and please correct me if anything wrong. Thanks!

hannn1
  • 61
  • 1
  • 2
  • 6
  • it didin't work bro, this code work exactly like my code, – Fariza Dec 05 '20 at 09:42
  • hmmm, i can only think of maybe the date format is wrong or the query has problem. Maybe you can try dd out the query to see whether is the query you want. If you want to see the query just change the get() to toSql() and dd the $infokeg. If the date has problem then maybe you can try using the Carbon instead of date(). – hannn1 Dec 05 '20 at 13:02
0

If you want to see what is run in the database use dd(DB::getQueryLog()) after query to see what queries exactly were run.

$infokeg = Infokeg::where('nama_kegiatan','like', "%" . $cari ."%")
    ->orWhere(function($query) use ($caritanggal) {
            $query->where('tanggal_kegiatan', $caritanggal);   
        })->paginate(10);
Jasim Juwel
  • 736
  • 8
  • 19
0

just make it into if condition

public function search(Request $request)
{
$cari = $request->search;
$caritanggal = $request->datekeg;
if (isset($cari)) {
    $infokeg = Infokeg::where('nama_kegiatan', 'like', '%'.$cari.'%')
    ->paginate(5);
}elseif (isset($caritanggal)) {
    $infokeg = Infokeg::where('tanggal_kegiatan', 'like', '%'.$caritanggal.'%')
    ->paginate(5);
}elseif (isset($cari)&&isset($caritanggal)) {
    $infokeg = Infokeg::where('nama_kegiatan', 'like', '%'.$cari.'%')
    ->orWhere('tanggal_kegiatan', 'like', '%'.$caritanggal.'%')
    ->paginate(5);
}
return view('/admin/infokeg/infokeg', ['infokeg' => $infokeg]);
}
Fariza
  • 33
  • 4