S
S
sr362019-12-26 17:32:57
Laravel
sr36, 2019-12-26 17:32:57

How to rewrite this code in Laravel?

Hello.
The task is to filter all users of the site, by the date the post was created.
Accordingly, we accept the date as input, we return only users.
At the moment, I get such a fierce govnokod.
What is the best way to rewrite it?

if($request->date) {
                $unixDate = strtotime($request->date);
                $year = date('Y',$unixDate);
                $month = date('m',$unixDate);
                $day = date('d',$unixDate);

                $posts = DB::table('posts')
                    ->select('user_id')
                    ->whereYear('created_at',$year)
                    ->whereMonth('created_at',$month)
                    ->whereDay('created_at',$day)
                    ->groupBy('user_id')
                    ->get()
                    ->pluck('user_id');
                $users = User::find($posts);
                return $users;
            }

I thought a little and wrote the following version.
Is it acceptable or can it still be improved?
$users = User::whereHas(
                'posts', function($q) {
                global $request;
                $unixDate = strtotime($request->date);
                $year = date('Y',$unixDate);
                $month = date('m',$unixDate);
                $day = date('d',$unixDate);
                $q->whereYear('created_at',$year);
                $q->whereMonth('created_at',$month);
                $q->whereDay('created_at',$day);
            }
            )->get();
            return $users;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NubasLol, 2019-12-26
@sr36

$users = User::whereHas('posts', function($q) use ($request) {
            $q->where('created_at', '>', \Carbon\Carbon::parse($request->date));
        }
        )->get();
        return $users;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question