How to Get Data Between Two Dates in Laravel 8

How to Get Data Between Two Dates in Laravel 8

Admin
Admin・ 22 September 2021
8 min read ・ 8854 views

Sometimes in creating a system or program, we need to add a date filter feature to get data according to the desired date (especially for systems or programs that have a report feature). And in this article, I will share a tutorial on how to get and display data with filter based on between two dates in Laravel 8.

$users = DB::table('users')
           ->whereBetween('votes', [1, 100])
           ->get();

To create a filter feature between two dates or between two values ​​in Laravel, we can use the provided query builder, whereBetween as in the example above. The whereBetween method verifies that the value in the column is between two predefined values.

Okay, let's get straight to the code πŸ‘‡ πŸ‘¨‍πŸ’»

Step 1: Install Laravel

//via Laravel Installer
composer global require laravel/installer
laravel new laravel-between-two-dates

//via Composer
composer create-project laravel/laravel laravel-between-two-dates

In this first step, we need to install the latest version of laravel (currently version 8) which we will use to implement create a data filter feature or retrieve and display data based on two dates. For laravel installation, you can use the laravel installer or use composer like the example above.

Please choose one method you want to use for laravel installation. From the two examples of laravel installation commands above, they will both generate a laravel project with the name laravel-between-two-dates.

Wait until the installation process is complete and when it's finished, don't forget to go to the project directory using the command cd laravel-between-two-dates.

Step 2: Setup Database

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

Next, create a new database to experiment with creating a data filter feature or fetch and display data based on between two dates in laravel 8. If you are using xampp as local development, please create a new database at localhost/phpmyadmin. Here I give an example, I created a new database with the name laravel-between-two-dates. Then don't forget to also adjust the DB_DATABASE in the .env file as in the example above.

Step 3: Create Model And Migration

php artisan make:model Registrant -m

Okay, then in the third step we need to create model and migration files for Registrant. Please run the command as above to generate Registrant model and migration files.

 public function up()
    {
        Schema::create('registrants', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamps();
        });
    }

Next, open the database/migrations/xxxx_xx_xx_xxxxxx_create_registrants_table.php file. We add an image field in the images table like the code above. If so, save and run the php artisan migrate command to migrate all migration files.

Step 4: Generate Dummy Data

php artisan make:factory RegistrantFactory --model=Registrant

We need dummy data to populate the registrants table. For that, we will create the dummy data using the factory in Laravel. Run the command as above to create a RegistrantFactory file with the target Registrant model.

 public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'created_at'=> $this->faker->dateTimeThisMonth($max = 'now', $timezone = null)  
        ];
    }

Then, open the RegistrantFactory file you just created in the database/factories/RegistrantFactory.php directory. In the method definition, change it to be as above.

php artisan tinker
Registrant::factory()->count(50)->create()

Next we generate dummy data using tinker. First, run the command php artisan tinker, then run the command Registrant::factory()->count(50)->create().

Step 5: Define Route & Logic

<?php
use Illuminate\Support\Facades\Route;
use Carbon\Carbon;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    if (request()->start_date || request()->end_date) {
        $start_date = Carbon::parse(request()->start_date)->toDateTimeString();
        $end_date = Carbon::parse(request()->end_date)->toDateTimeString();
        $data = App\Models\Registrant::whereBetween('created_at',[$start_date,$end_date])->get();
    } else {
        $data = App\Models\Registrant::latest()->get();
    }
    
    return view('welcome', compact('data'));
});

In the fifth step, we need to create the logic to display data based on between two dates in laravel 8. For example, we will create the logic in routes/web.php or rather in Route::get('/').

Open the routes/web.php file, then change the existing code to be as above. Here we add logic, if there is a request()->start_date or there is a request()->end_date, it will display the registrant data with the created_at data between the selected date (start_date and end_date). But if there are no two requests, it will display all data from the registrant table.

Step 6: Setup View

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
        <title>Get Data Between Two Dates in Laravel 8</title>
    </head>
    <body>
        <div class="container my-4">
            <div class="row">
                <h2 class="fs-3 text-center my-3">Get Data Between Two Dates in Laravel 8</h2>
                <div class="my-2">
                    <form action="/" method="GET">
                        <div class="input-group mb-3">
                            <input type="date" class="form-control" name="start_date">
                            <input type="date" class="form-control" name="end_date">
                            <button class="btn btn-primary" type="submit">GET</button>
                        </div>
                    </form>
                </div>
                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Name</th>
                            <th scope="col">Email</th>
                            <th scope="col">Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($data as $key => $data)
                        <tr>
                            <th scope="row">{{ ++$key }}</th>
                            <td>{{ $data->name }}</td>
                            <td>{{ $data->email }}</td>
                            <td>{{ $data->created_at }}</td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
        <!-- Option 1: Bootstrap Bundle with Popper -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
    </body>
</html>

Okay, in the last step we change all the code in the welcome.blade.php file to be like the code above. Here we make it simple, that is, just display the data in the table and add a form for date filters (start_date and end_date).

Step 7: Testing

Laravel 8: get data between two dates

After going through the steps, starting from installing laravel to the setup view step, at the end of this tutorial article we will try to filter data based on two dates in laravel 8. Please run the laravel project by running the php artisan serve command, then open the project in a browser . Then try to filter the data by selecting the start date and end date like the example picture above.

Thus the tutorial article displays data based on two dates in laravel 8 this time. You can improve the code in this article according to your project needs. Hopefully this article can be useful, good luck and see you in the next article. πŸ‘‹

Happy coding. πŸš€ πŸ‘¨‍πŸš€ πŸ‘¨‍πŸ’»

Tinggalkan Komentar
Loading Comments