Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, how to filter date in views?

I have my views setup more or less like the picture below or can see it on jsfiddle https://jsfiddle.net/t37g4yzp/1/

How to filter the date in the table base on the user input Start Date and End date in views?

Controller

public function index()
{
  $get_all_user = User::all();
  return view('userPage.index', compact('get_all_user'));
}

enter image description here

like image 820
LearnProgramming Avatar asked Oct 27 '25 05:10

LearnProgramming


1 Answers

This is the way I do date filtering. In order to catch the start data and end date inject the Request Object in to the index method.Then I would validate the data submitted and I convert the dates in to Carbon Object which give more options like formatting the dates.lastly I use whereDate eloquent query function to compare dates. So the end result would be something like this.

public function index(Request $request)
{
  this->validate($request,[
   'start_date' => 'required|date',
   'end_date' => 'required|date|before_or_equal:start_date',
  ]);

  $start = Carbon::parse($request->start_date);
  $end = Carbon::parse($request->end_date);

  $get_all_user = User::whereDate('date','<=',$end->format('m-d-y'))
  ->whereDate('date','>=',$start->format('m-d-y'));

  return view('userPage.index', compact('get_all_user'));
}
like image 178
Chamara Abeysekara Avatar answered Oct 28 '25 18:10

Chamara Abeysekara