Laravel Where Clause with Function Query Example

By Hardik Savani April 16, 2024 Category : Laravel

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...

Tags :
Shares