Laravel Where Clause with Function Query Example
Hey Guys,
This post will give you an example of laravel eloquent where function query. you will learn laravel where clause with function. This article goes in detailed on laravel where function query. It's a simple example of how to use function with where clause laravel.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.
Laravel eloquent provides where clause query. But if you want to use multiple where conditions with or where then how you will use with laravel eloquent. Then laravel provides the where condition with a function query. So Here, I will give you a simple example of how to use a function with where clause in laravel eloquent. let's see a simple example.
Example 1: Laravel where() Clause with Function Query
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$posts = Post::select("*")
->where("is_published", 1)
->where(function($query) {
$query->where('category', 'Laravel')
->orWhere('viewer', '>', 100);
})
->get();
dd($posts);
}
}
Query:
SELECT * FROM posts
WHERE is_published == 1 AND (category = 'Laravel' OR viewer > 50)
Example 2: Laravel orWhere() Clause with Function Query
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$posts = Post::select("*")
->where("viewer", ">", 100)
->orWhere(function($query) {
$query->where('category', 'Laravel')
->where('viewer', '>', 50);
})
->get();
dd($posts);
}
}
Query:
SELECT * FROM posts
WHERE viewer > 100 OR (category = 'Laravel' AND viewer > 50)
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 whereRelation() Condition Example
- Laravel Eloquent whereHas() Condition Example
- Laravel Eloquent Left Join Where Null Condition Example
- Laravel Eloquent whereNotNull() Query Example
- Laravel Eloquent whereNull() Query Example
- 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 Eloquent Where Like Query Example Tutorial
- Laravel Where Clause with MySQL Function Example
- Laravel Query Builder Where Exists Example