Search code examples
phpmysqllaravel-5.3

How to us timestamp in query builder in laravel 5.3 to tack users registered in last 5 days


I want to list down the users who are registered in last 5 day.. To list down all the users 1 use following query..

$users = User::select('*')->orderby('created_at', 'desc')->get();

and fetch it in view like this.

<table class="table table-hover">
                            <tbody><tr>
                                <th>ID</th>
                                <th>User Name</th>
                                <th>Email</th>
                                <th>Country</th>
                                <th>Date</th>
                                <th>Points</th>
                            </tr>

                            <?php foreach ( $users as $u ){ ?>

                            <tr>
                                <td>{{ $u->id }}</td>
                                <td>{{ $u->user_name }}</td>
                                <td>{{ $u->email }}</td>
                                <td>{{ $u->country }}</td>
                                <td>{{ $u->created_at }}</td>
                                <td>{{ \App\Points::getUserPoints($u->id) }}</td>
                            </tr>



                            <?php }?>

                            </tbody></table>

but what will be the query to fetch users who have registered in last 5 days..?? any one please tell me a good query..


Solution

  • You can use Carbon (docs) to do this:

        $now = Carbon::now();
        $users = User::where('created_at', '>=', $now->subDays(5))->get();
    

    Make sure to "use Carbon\Carbon;" at the top of the file.