Retrive records where updated_at is older than created_at with 2 hours in Laravel (eloquent)
Asked Answered
M

3

4

I want to count records where updated_at is 2 hours older than created_at.

Code

$teLang = $kentekens->where('updated_at', '>', 'created_at'->subHours(2));

Unfortunately this doesn't work because subHours(2) is for carbon but hopefully you get the idea.

View

<h1>{{ $teLang->count() }}</h1>

Controller

public function create() {
        $kentekens = Kenteken::latest()
            ->where('created_at', '>=', Carbon::today())
            ->get();

        $teLang = $kentekens->where('updated_at', '>', 'created_at'->subHours(2));

        return view('layouts.dashboard', compact('kentekens', 'teLang'));
    }

anyone know how?

Memorize answered 23/1, 2018 at 19:10 Comment(1)
Does this post help?Joyjoya
M
4
$kentekens->whereRaw('`updated_at` > DATE_ADD(`created_at`, INTERVAL 2 HOUR)');

SQL:

select `id` from `tablename` where `updated_at` > DATE_ADD(`created_at`, INTERVAL 2 HOUR)
Mushy answered 23/1, 2018 at 19:52 Comment(0)
V
2

Use the filter() method. Using your code logic:

$teLang = $kentekens->filter(function($i) {
    return $i->updated_at->gt($i->created_at->subHours(2));
});

Using this statement "where updated_at is 2 hours older than created_at":

$teLang = $kentekens->filter(function($i) {
    return $i->updated_at->lt($i->created_at->subHours(2));
});
Vitascope answered 23/1, 2018 at 19:17 Comment(1)
Using the gt returns a row that shouldn't be included where 'created_at' = 2018-01-24 16:59:12 and 'updated_at' = 2018-01-24 17:44:32. This shouldn't be happening?Memorize
U
0

Maybe so?

public function create() {
    $kentekens = Kenteken::latest()
        ->where('created_at', '>=', Carbon::today())
        ->get();
    $cr = Carbon::create($kentekens->created_at);
    $teLang = $kentekens->where('updated_at', '>', $cr->addHours(2));

    return view('layouts.dashboard', compact('kentekens', 'teLang'));
}
Ultrastructure answered 23/1, 2018 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.