Laravel Where Clause with MySQL Function Example

By Hardik Savani November 5, 2023 Category : Laravel MySql

Hey Developer,

This tutorial is focused on laravel where clause with mysql function. This tutorial will give you a simple example of laravel eloquent where mysql functions. let’s discuss about laravel whereRaw mysql function. we will help you to give an example of laravel where clause sql function example. Let's see below example mysql function mysql laravel.

When you are working on laravel projects and you need to use mysql function in where clause then you can easily use that using DB::raw() and whereRaw(). In this example you can show how to i use mysql function in where clause. In this example i want to compare with year of created_at field but not whole date, that's whay i use mysql function Year(), this function will return only year from timestamp and compare with given value. I add two example of how to use sql function in where cause. let's See both example.

Example 1:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Item;

use DB;

class ProductController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$data = Item::select("items.*")

->where(DB::raw("Year(items.created_at)"),'2022')

->orderBy('items.created_at')

->get();

dd($data);

}

}

Example 2:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Item;

use DB;

class ProductController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$data = Item::select("items.*")

->whereRaw(DB::raw("Year(items.created_at) = '2016'"))

->orderBy('items.created_at')

->get();

dd($data);

}

}

I hope it can help you...

Tags :
Shares