Laravel Where Clause with date_format() Example

By Hardik Savani April 16, 2024 Category : Laravel

Hey Developer,

In this short tutorial, we will share the quick and straightforward way to laravel where with date_format. If you have a question about db::raw date format laravel then I will give a simple example with a solution. I explained simply about laravel where date_format() sql. We will use laravel date_format sql example.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

In this post, i share with you that how to use date_format() with where condition of Laravel query builder. When i was working on my project, i require to search with get only selected month and year records from created_at(timestamp) column. I was thinking how can i but i know date_format() of mysql. but don't know how to use in laravel where clause. At last i use DB::raw() of Laravel and it's work.

If you have also need to search this way then you can do it this way:

Example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Item;

use DB;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$data = Item::select("id","title","created_at")

->where(DB::raw("(DATE_FORMAT(created_at,'%Y-%m'))"),"2022-07")

->get();

dd($data);

}

}

I hope it can help you...

Tags :
Shares