Reusable Date Filter Using Traits in Laravel Eloquent
Eloquent is an object-relational mapper (ORM) built into Laravel, which makes it fun to interact with your database. When using Eloquent, each database table has an associated “Model” that is used to interact with that table. In addition to retrieving records from database tables, Eloquent models also allow you to insert, update, and delete records from tables.
Now we will create a reusable trait to filter a date in a table using laravel 10. You can develop your own code on what kind of filter you want to use.
Step 1 : Create laravel project
This step is optional, if you already have an existing Laravel project, please skip this step and go directly into your Laravel project.
Open a terminal or command prompt and type the following command.
composer create-project laravel/laravel laravel-traits
cd laravel-traitsStep 2 : Create a trait
Next, we create a folder with the name Traits in ./laravel-traits/app/ folder and we create a file with the name FilterByDate.php in that folder so the complete address will be ./laravel-traits/app/Traits/FilterByDate.php then enter the following code
<?php
namespace App\Traits;
trait FilterByDate
{
public function scopeWhereDateBetween($query, $startDate, $endDate)
{
return $query->whereBetween($this->getTable() . '.' . $this->getCreatedAtColumn(), [$startDate, $endDate]);
}
public function scopeWhereDateIs($query, $date)
{
return $query->where($this->getTable() . '.' . $this->getCreatedAtColumn(), $date);
}
}So we will create two filters, the first filter between two dates and the second filter based on a specific date, if you want to add your own you can create your own criteria.
Step 3 : Modify the user model
Modify the user model at the address ./app/Models/User.php so that it becomes the following code
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Traits\FilterByDate;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, FilterByDate;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}Step 4: Make user seeder
Create user seeder with following code
php artisan make:seeder UserSeederThis command will create a new file at ./database/seeders/UserSeeder.php, open the file and change it to the following code
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
User::create([
'name' => 'User 1',
'email' => 'user1@server.com',
'password' => Hash::make('12345'),
'created_at' => '2023-01-01 12:01:00',
]);
User::create([
'name' => 'User 2',
'email' => 'user2@server.com',
'password' => Hash::make('12345'),
'created_at' => '2023-02-05 03:45:01',
]);
User::create([
'name' => 'User 3',
'email' => 'user3@server.com',
'password' => Hash::make('12345'),
'created_at' => '2023-02-05 15:32:11',
]);
User::create([
'name' => 'User 4',
'email' => 'user4@server.com',
'password' => Hash::make('12345'),
'created_at' => '2023-02-06 21:01:55',
]);
}
}Open file ./database/seeders/DatabaseSeeder.php and change it to the following code
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// add this line
$this->call(UserSeeder::class);
}
}Step 5: Create a controller for testing
Create Test controller
php artisan make:controller TestControllerThen add this code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class TestController extends Controller
{
public function index(): View
{
dd( User::whereDateBetween('2023-02-01 00:00:00','2023-02-06 23:59:59')->get()->toArray() );
}
}We will try to filter users based on created date.
Get Akhmad Shaleh’s stories in your inbox
Join Medium for free to get updates from this writer.
Step 6 : Add routes
Open the ./routes/web.php file and add the following code
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
return view('welcome');
});
Route::get('/test', [TestController::class,'index']);Step 7 : Setup database configuration
Open the .env file and adjust the following configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=Step 8 : Run migration
Open a terminal or command prompt and type the following command
php artisan migrate:fresh --seedIf you get an error like the following picture
You can fix this by opening the file ./app/Providers/AppServiceProvider.php and adding the following code
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Schema::defaultStringLength(191);
}
}Try again to run the `php artisan migrate:fresh — seed` command
Step 9 : Run php artisan serve
To test whether your traits are working, let’s try running PHP Artisan Serve
php artisan serveOpen a browser and type the address http://127.0.0.1:8000/test
You will get User 2, User 3 and User 4. Why doesn’t User 1 exist because User 1 was created on 2023–01–01 while the user we are querying for was created between 2023–02–01 and 2023–02–06.
Conclusion
You can create traits that are reusable and maintenable. It can be used anywhere in the Laravel application besides models. You can also use this trait on models other than the user model as long as the column criteria names are the same or the column names can be included in parameters.
Happy Coding.







