T
T
TanykaGURU2020-12-25 18:11:19
Laravel
TanykaGURU, 2020-12-25 18:11:19

Is there a method in Laravel that sets a start date to look up information in a database without first finding it?

Hai!

Is there a method in Laravel that sets a start date to look up information in a database without first finding it?

Let's say I want to get all the data for a certain interval:

$dateEnd = new DateTime('2020-11-01');
$end = $dateEnd->format('Y-m-d')

Model::whereDate('created_at', '>=', 'ЧТО ЗДЕСЬ?')->whereDate('created_at', '<=', $end)->get();

Tried adding like this:
$dateStart = new DateTime('2018-11-01');
$start = $dateStart->format('Y-m-d')

But if there is no data from 2018-11-01 in the database, then an error occurs.
So how can you add a start date without making an extra query to the database?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arman, 2020-12-25
@TanykaGURU

Somewhere you have an error, the database cannot give errors on the correct request, it will simply return an empty result.
if you only know the date "To", then just do not put "From".

$query = Model::query();
if($from) {
    $query->whereDate('created_at', '>=', $from);
}
if($to) {
    $query->whereDate('created_at', '<=', $to);
}
$result = $query->get();

I
Ilya Chubarov, 2020-12-25
@agoalofalife

If it's just a request, you can do this

$from = date('2018-11-01');
$to = date('2020-11-01');
// или Carbon

$from = Carbon::parse('2018-11-01')->toDateTimeString();

Model::whereBetween('created_at', [$from, $to])->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question