article

Monday, March 13, 2023

Laravel Date Filters Today Yesterday This Week Last Week This Month Last Month This Year Last Year

Laravel Date Filters Today Yesterday This Week Last Week This Month Last Month This Year Last Year

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel>composer create-project --prefer-dist laravel/laravel my-app

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create Controller EmployeeController
php artisan make:controller EmployeeController
C:\xampp\htdocs\laravel\my-app>php artisan make:controller EmployeeController
app\Http\Controllers\EmployeeController.php

//app\Http\Controllers\EmployeeController.php
<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Carbon;

class EmployeeController extends Controller
{
    public function index(Request $request): Response
    {
        $query = Employee::query();
        $dateFilter = $request->date_filter;

        switch($dateFilter){
            case 'today':
                $query->whereDate('created_at',Carbon::today());
                break;
            case 'yesterday':
                $query->wheredate('created_at',Carbon::yesterday());
                break;
            case 'this_week':
                $query->whereBetween('created_at',[Carbon::now()->startOfWeek(),Carbon::now()->endOfWeek()]);
                break;
            case 'last_week':
                $query->whereBetween('created_at',[Carbon::now()->subWeek(),Carbon::now()]);
                break;
            case 'this_month':
                $query->whereMonth('created_at',Carbon::now()->month);
                break;
            case 'last_month':
                $query->whereMonth('created_at',Carbon::now()->subMonth()->month);
                break;
            case 'this_year':
                $query->whereYear('created_at',Carbon::now()->year);
                break;
            case 'last_year':
                $query->whereYear('created_at',Carbon::now()->subYear()->year);
                break;                       
        }
            
        $employees = $query->get();

        return response()->view('index',compact('employees','dateFilter'));
    }
}
Database Migration
php artisan make:model Employee -m
C:\xampp\htdocs\laravel\my-app>php artisan make:model Employee -m
database/migrations/create_employees_table.php
//database/migrations/create_employees_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('last_name');
            $table->string('email');
            $table->string('gender');
            $table->string('position');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('employees');
    }
};
run this migration
C:\xampp\htdocs\laravel\my-app>php artisan migrate

CREATE TABLE `employees` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `gender` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `position` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


INSERT INTO `employees` (`id`, `name`, `last_name`, `email`, `gender`, `position`, `created_at`, `updated_at`) VALUES
(1, 'Cairocoders', 'Ednalan', 'cairocoders@gmail.com', 'Male', 'Coder', '2023-03-01 12:34:10', '2023-03-01 12:34:10'),
(2, 'Clydey', 'Ednalan', 'clyde@gmail.com', 'Male', 'Coder', '2023-02-01 12:34:10', '2023-02-01 12:34:10'),
(3, 'Airi', 'Satou', 'Satou@gmail.com', 'Female', 'Accountant', '2023-01-01 00:24:05', '2023-01-01 00:24:05'),
(4, 'Angelica', 'Ramos', 'AngelicaRamos@gmail.com', 'Female', 'Chief Executive Officer (CEO)', '2023-01-16 00:24:05', '2023-01-16 00:24:05'),
(5, 'Ashton', 'Cox', 'AshtonCox@gmail.com', 'Male', 'Junior Technical Author', '2022-12-07 00:32:02', '2022-12-07 00:32:02'),
(6, 'Bradler', 'Greer', 'Bradley Greer@gmail.com', 'Male', 'Software Engineer', '2022-10-18 00:32:02', '2022-10-18 00:32:02'),
(7, 'Brenden', 'Wagner', 'Brenden Wagner@gmail.com', 'Male', 'Software Engineer', '2023-01-05 01:02:56', '2023-01-05 01:02:56'),
(8, 'Brielle', 'Williamson', 'Brielle Williamson@gmail.com', 'Female', 'Integration Specialist', '2023-03-14 01:02:56', '2023-03-14 01:02:56'),
(9, 'Bruno', 'Nash', 'Bruno Nash@gmail.com', 'Male', 'Software Engineer', '2023-03-15 01:05:46', '2023-03-15 01:05:46'),
(10, 'Caesar', 'Vance', 'Caesar Vance@gmail.com', 'Male', 'Pre-Sales Support', '2023-03-14 01:05:46', '2023-03-14 01:05:46'),
(11, 'Cara', 'Stevens', 'Cara Stevens@gmail.com', 'Female', 'Sales Assistant', '2023-03-15 01:07:04', '2023-03-15 01:07:04'),
(12, 'Cedric', 'Kelly', 'Cedric Kelly@gmail.com', 'Male', 'Senior Javascript Developer', '2023-03-13 01:07:04', '2023-03-13 01:07:04');

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Datatables
https://datatables.net/examples/basic_init/zero_configuration.html

resources/views/index.blade.php
//resources/views/index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel Date Filters Today Yesterday This Week Last Week This Month Last Month This Year Last Year</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
</head>
<body>
    <div class="container">
        <h1 class="text-center text-success pt-4">Laravel Date Filters Today Yesterday This Week Last Week This Month Last Month This Year Last Year</h1>
        <hr>
    <div class="row py-2">
        <div class="col-md-6">
            <h2>List of Empoyees</h3>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label for="date_filter">Filter by Date:</label>

                <form method="get" action="employee">
                    <div class="input-group">
                        <select class="form-select" name="date_filter">
                            <option value="">All Dates</option>
                            <option value="today" {{ $dateFilter == 'today' ? 'selected' : '' }}>Today</option>
                            <option value="yesterday" {{ $dateFilter == 'yesterday' ? 'selected' : '' }}>Yesterday</option>
                            <option value="this_week" {{ $dateFilter == 'this_week' ? 'selected' : '' }}>This Week</option>
                            <option value="last_week" {{ $dateFilter == 'last_week' ? 'selected' : '' }}>Last Week</option>
                            <option value="this_month" {{ $dateFilter == 'this_month' ? 'selected' : '' }}>This Month</option>
                            <option value="last_month" {{ $dateFilter == 'last_month' ? 'selected' : '' }}>Last Month</option>
                            <option value="this_year" {{ $dateFilter == 'this_year' ? 'selected' : '' }}>This Year</option>
                            <option value="last_year" {{ $dateFilter == 'last_year' ? 'selected' : '' }}>Last Year</option>
                            </select>
                        <button type="submit" class="btn btn-primary">Filter</button>
                    </div>
                </form>

            </div>
        </div>
    </div>
    <table id="example" class="table  table-bordered table-hover display">
        <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Last Name</th>
                    <th>Position</th>
                    <th>Gender</th>
                    <th>E-mail</th>
                    <th>Date Created</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($employees as $employee)
                <tr>
                    <td>{{ $employee->id }}</td>
                    <td>{{ $employee->name }}</td>
                    <td>{{ $employee->last_name }}</td>
                    <td>{{ $employee->position }}</td>
                    <td>{{ $employee->gender }}</td>
                    <td>{{ $employee->email }}</td>
                    <td>{{ $employee->created_at->format('Y-m-d H:i:s') }}</td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script>
 $(document).ready(function () {
    $('#example').DataTable();
});
</script>
</body>
</html>
Routes
routes/web.php
//routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/employee',[EmployeeController::class,'index']);
Run C:\xampp\htdocs\laravel\my-app>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post