How To Use Where Clause With Two Fields Of The Same Table Examples

  • 11-08-2022
  • 1152
  • Laravel 9
  • Haresh Chauhan

In this whereColumn() laravel eloquent method, I will teach you how to use whereColumn in the same database table with two columns. When you want to where clause in the same table that time this laravel eloquent whereColumn() method will help you to compare two columns with where clause.

This whereColumn() clause is compared tow column in the same table, When you want to make where conditional data retrieve clause in each other column with same table column this example will help you various way to use in laravel eloquent model.

Example With Query

See in this example, I have two columns in the database table, I want to fetch that class student record which class has boys grater than the girl, So in this can I will query in same table two column like this.

Laravel JSON Data Search/Filter From Database Example

$query->whereColumn('boy','>','girl')

Here is an example, I have an offering table inside my database, I want to fetch that offer that has a lower number of number_of_applied users than number_of_applicable (number_of_applicable(10) > number_of_applied(15)) will come to that offer only.

<?php
use App\Models\Offer;

Offer::select(
    'id',
    'name',
    'description',
    'promocode',
    'image',
    'description',
    'min_bill_amount',
    'valid_from',
    'valid_to',
)
->where('valid_from', '<=', now()->format('Y-m-d H:i:s'))
->where('valid_to', '>=', now()->format('Y-m-d H:i:s'))
->whereColumn('number_of_applicable','>','number_of_applied') // HERE
->where('status',1)
->orderBy('created_at','desc')
->paginate(perPage());

In this example, you can see, that I want users who have the same name and username with who has their student mobile number the same as their parent's mobile number.

use App\Models\User;

User::whereColumn([
    ['name', '=', 'username'],
    ['student_mobile_no', '=', 'parent_mobile_no'],
])->get();

Fetch booking details, Who customer has their booking date time is future date then who booked booking date.

use App\Models\Booking;

Booking::whereColumn('booking_date_time', '>','created_at')
->get();

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :