Ruka Xing
Ruka Xing

Reputation: 642

Laravel 5.7 search by date

Question is: How to search by date and by description? What's my problem? I think it could work but it doesn't work at all.

Controller

public function index(Request $request)
{   
    $search = $request->get('search');
    $date = $request->get('date');
    $projects = Project::where('description', 'like', '%' . $search . '%')
      ->orWhere('created_at', '%Y-%m-%d','LIKE', '%'.$date.'%')
      ->orderBy("created_at", 'desc')
      ->paginate(10)
      ->withPath('?search=' . $search);

    return view('projects.index', compact('projects'));

View

<div class="col-sm-12 form-group">
  <div class="input-group">
   <input class="form-control" name="date" type="date" > 
   <input class="form-control" name="search" type="text"/>
   <div class="input-group-btn">
     <button type="submit" class="btn btn-success">Search</button>
   </div>         
 </div>
</div>

Upvotes: 1

Views: 6136

Answers (2)

Hamelraj
Hamelraj

Reputation: 4826

You can use ->whereDate() instead of ->where()

$projects = Project::where('description', 'like', '%' . $search . '%')
   ->whereDate('created_at',$date)
   ->orderBy("created_at", 'desc')
   ->paginate(10)
   ->withPath('?search=' . $search);

if above not working then try this

$projects = Project::where('description', 'like', '%' . $search . '%')
        ->orWhere(function ($query) use ($date) {
          $query->whereDate('created_at',$date);
        })
       ->orderBy("created_at", 'desc')
       ->paginate(10)
       ->withPath('?search=' . $search);

check this Link 1 and this also Link2

Upvotes: 3

Dhruv Raval
Dhruv Raval

Reputation: 1583

You can use whereDate()

...
->whereDate('created_at', '=', $date)
...

and if you want to use OR where then

->orWhere(function ($query) use ($date){
    $query->whereDate('created_at', '=', $date);
});

Upvotes: 1

Related Questions