Ad

Eloquent Model Between Dates Format D.m.Y

- 1 answer

I have column "exp_date" with type of string, format of column is d.m.Y. I want to get records between two dates.

I am trying like with this code:

$start = '10.09.2016';
$end = '20.10.2018';

$company->records()->whereBetween('exp_date', [$start, $end])->get();
Ad

Answer

Simply use carbon package which extends the native PHP DateTime class.

EXAMPLE 1 : DATABASE COLUMN TYPE IS SET TO date OR dateTime $start = '10.09.2016'; $end = '20.10.2018';

$start = Carbon::createFromFormat('d-m-Y',  $start)->toDateTimeString(); 
$end = Carbon::createFromFormat('d-m-Y',  $end)->toDateTimeString();

Then create query

$company = Records::where(function($q){
    $q->where('exp_date', '<=',$start );
    $q->where('exp_date', '>', $end);

});

$company->get();

EXAMPLE 2 : DATABASE COLUMN TYPE IS SET TO varchar

Here you will have to first of all covert existing table column via migrations . Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file.

php artisan make:migration update_exp_to_records_table --table=records

Edit the migration file , add below relevant to your table names

Schema::table('records', function ($table) {
    $table->string('expire')->date()->change();
});

Run only this specific migration Then use example 1 above in your controller function.

Ad
source: stackoverflow.com
Ad