Laravel Where Clause with MySQL Function Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent whereHas() Condition Example
- Laravel Eloquent Left Join Where Null Condition Example
- Laravel Eloquent take() and skip() Query Example
- Laravel Eloquent whereNull() Query Example
- Laravel Eloquent orWhere() Condition Example
- Laravel Has Many Through Eloquent Relationship Tutorial
- Laravel WhereIn() and WhereNotIn() with Subquery Example
- Laravel - whereDate(), whereMonth(), whereDay() and whereYear() Example
- Laravel Where Condition with Two Columns Example
- Laravel Where Clause with date_format() Example
- Laravel Group By with Month and Year Example
- Laravel Eloquent Where Like Query Example Tutorial
- Laravel Join with Subquery in Query Builder Example