We can search data using the like operator in Laravel 10 very easily. But in this tutorial, we will search or filter data between two dates in Laravel 10 application. So from this laravel wherebetween tutorial, you will see how to search data between two dates in laravel 10.

Laravel provides whereBetween() helper that accepts an array and database column and using this we can easily search or filter data between two dates. We will create a simple form and I will put two input fields one is date_from and the other is date_to. When a user clicks a search button, we will fetch data from the database according to the date_from and date_to values using whereBetween.

Let's see the preview of this laravel 10 search data between two dates from the below image.

laravel-10-search-data-between-two-dates

Step 1: Download Fresh Laravel 10

In the first step of getting data by date in Laravel, download a fresh Laravel application by the following command:

composer create-project laravel/laravel example-app

 

Step 2: Create Migration

In this step, we need to create a migration and model for generating a employees table. So run the below command to create employees table.

php artisan make:model Employee -m

 

Now update the migration like below:

database/migrations

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->date('joining_date')->nullable();
            $table->integer('joining_salary');
            $table->boolean('is_active')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('employees');
    }
};

 

And now update the model like along with protected property guard to avoid mass assignment error:

app/Models/Employee.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    use HasFactory;

    protected $guarded = [];
}

 

Step 3: Connect database

In this step, we will connect the database, and I am going to use MySQL. So connect it like the below by updating the .env file:

.env

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

 

Now run the migration command:

php artisan migrate

 

Read also: Laravel 10 Algolia Full Text Search Tutorial

 

Step 4:  Create Route

Now in this, I will use one route to search or filter data between two dates. you can create two route for that. 

routes/web.php

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('employee', [EmployeeController::class,'index'])->name('employee.index');

 

Step 5: Create Controller

Now in this step, we have to create an EmployeeController to define this index method to laravel where between two columns.

php artisan make:controller EmployeeController

 

Now update the controller like:

app/Http/Controllers/EmployeeCountroller.php

<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;

class EmployeeController extends Controller
{
    public function index(Request $request)
    {
        $employees = Employee::orderBy('id', 'desc')
            ->when(
                $request->date_from && $request->date_to,
                function (Builder $builder) use ($request) {
                    $builder->whereBetween(
                        DB::raw('DATE(created_at)'),
                        [
                            $request->date_from,
                            $request->date_to
                        ]
                    );
                }
            )->paginate(5);

        return view('employee.index', compact('employees', 'request'));
    }

}

 

Step 6: Create Views

We are almost there. Just we have to create our list file with all the employee list with the search form.

  • index.balde.php
  • app.blade.php

So create these files inside the following path and update them like below:

resources/views/layouts/app.blade.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ config('app.name', 'Laravel') }}</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body style="background: #ddd;">
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
                        <span class="sr-only">Toggle Navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="{{ url('/employee') }}" style="margin-left:190px;">Laravelia</a>
                </div>
                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <ul class="nav navbar-nav">
                        &nbsp;
                    </ul>
                        <ul class="nav navbar-nav navbar-right" style="margin-right:190px;">
                        @guest
                            <li><a href="{{ route('login') }}">Login</a></li>
                            <li><a href="{{ route('register') }}">Register</a></li>
                        @else
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>
        
                                <ul class="dropdown-menu">
                                    <li>
                                        <a href="{{ route('account.index') }}">Account</a>
                                    </li>
                                    <li>
                                        <a href="{{ route('logout') }}"
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                            Logout
                                        </a>
        
                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>        
        <div class="container">
            <div class="col-md-2"></div>
            <div class="col-md-8">
                @yield('content')
            </div>
            <div class="col-md-2"></div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</body>
</html>

 

This page for showing all the employee lists.

resources/views/employee/index.blade.php

@extends('layouts.app')

@section('content')
    @if (session()->has('success'))
        <div class="alert alert-success">
            {{ session()->get('success') }}
        </div>
    @endif
    <div class="panel panel-default">
        <div class="panel-body">
            
            <form action="{{ route('employee.index') }}" method="get">
                 <div class="row">
                    <div class="col-md-5 form-group">
                        <label for="">Date From</label>
                        <input type="date" name="date_from" class="form-control" value="{{ $request->date_from }}">
                     </div>
                     <div class="col-md-5 form-group">
                        <label for="">Date From</label>
                        <input type="date" name="date_to" class="form-control" value="{{ $request->date_to }}">
                     </div>
                     <div class="col-md-2 form-group" style="margin-top:25px;">
                        <input type="submit" class="btn btn-primary" value="Search">
                     </div>
                 </div>
            </form>

            <strong>Employee List</strong>
            <a href="{{ route('employee.create') }}" class="btn btn-primary btn-xs pull-right py-0">Create Employee</a>
            <table class="table table-responsive table-bordered table-stripped" style="margin-top:10px;">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($employees as $employee)
                    <tr>
                        <td>{{ $employee->id }}</td>
                        <td>{{ $employee->name }}</td>
                        <td>{{ $employee->email }}</td>
                        <td><span type="button" class="btn btn-{{ $employee->is_active ? 'success' : 'danger' }} btn-xs py-0">{{ $employee->is_active ? 'Active' : 'Inactive' }}</span></td>
                        <td style="display:inline-flex;">
                            <a href="{{ route('employee.show',$employee->id) }}" class="btn btn-primary btn-xs py-0" style="margin:2px;">Show</a>
                            <a href="{{ route('employee.edit',$employee->id) }}" class="btn btn-warning btn-xs py-0" style="margin:2px;">Edit</a>
                            <form action="{{ route('employee.destroy',$employee->id) }}" method="post">
                                @csrf
                                @method('delete')
                                <button type="submit" class="btn btn-danger btn-xs py-0" style="margin:2px;">Delete</button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            {{ $employees->links() }}
        </div>
    </div>
@endsection

 

Now all are set to go. Now run php artisan serve command to start the development server and visit the following URL to check search data between two dates in laravel.

URL
http://localhost:8000/employee

 

Read also: Laravel 10 Scout Full Text Search Example

 

Conclusion

I have tried my best to show you this laravel where date between two columns. Now we know laravel 10 search data between two dates. Hope this laravel where between two columns tutorial will help you to create how to search data between two dates in laravel?.

Category : #laravel

Tags : #laravel , #laravel search