Laravel where() and orWhere() condition together for one column

2 years ago
456 views

If you are in a situation where you need to use Laravel where() and orWhere() condition together for one column, this tip might be helpful for you. Let's dig into a real life scenario.

Imagine that, I am checking send_at column. It can be both, either null or have timestamp value.

What need to achieve?

  • Get records if send_at is null.
  • Get records also if send_at has value and then add a condition on that value. Probably time in certain time ago.

Appointment::whereNull('send_at')
    ->orWhere(function($query) {
        $query->whereNotNull('send_at')
            ->where('send_at', '<', now()->subMinutes(50)]);
    })->get()

This code will check-

  • Whether send_at value is null or not.
  • If it has value, then check whether the send_at value is less than 50 minutes ago from now or not.

Hope it will help you.

Thanks.

Thouhedu Islam Suchi

Thouhedul Islam

Laravel Developer

Hi, I am a Laravel Developer with a passion for web development. I specialize in PHP, particularly Laravel, as well as Javascript, MySql, and other cutting-edge web technologies.

During the day, I work for GLEIF, where I apply my skills and experience to develop innovative web applications. At night, I enjoy contributing to the community and solving problems. You can often find me on Laracasts, where I love to stay active and keep up-to-date with the latest trends in web development.

I am excited about the potential of technology and its power to transform people's lives.