Data between two dates with whereBetween in Laravel.

Data between two dates with whereBetween in Laravel.

I have come across many instances where I need to retrieve data created between two dates. It can be done with multiple where conditions, but it's far better to use whereBetween method of laravel eloquent. Following is an example of using whereBetween in a laravel query. This whereBetween example will help you deal with this requirement.

Let's assume we need to retrieve blog posts created in the last one week. Checkout the following code.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use Carbon\Carbon;

class PostController extends Controller
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
    public function index()
        $old_date = Carbon::now()->subDays(7);
        $current_date = Carbon::now();

        $posts = Post::whereBetween('created_at', [ 
                   $old_date, $current_date ])->get();

        // Return $posts here.

Laravel eloquent whereBetween method is not just for dates. It can be used for finding data between any two numbers as well. I hope this example for retrieving data between two dates is helpful to you.