Home / Snippets / How to Query Column That is Not Null In Laravel
How to Query Column That is Not Null In Laravel cover

How to Query Column That is Not Null In Laravel

6K

3 years ago

0 comments

To query a column that's not null in Laravel, you can make use of the "whereNotNull()" function available to every query builder. By using this function you instruct the query builder to check against the NULL value of the database so you will get the result directly as you intended it to be.

Laravel Eloquent whereNotNull


When querying your Laravel Eloquent you can directly chain the "whereNotNull()" from the model itself.
<?php

$posts = Post::query()
    ->whereNotNull('published_at')
    ->get();

Laravel Query Builder whereNotNull


If you do prefer using the "DB" facade then you can write your code with the "whereNotNull()" condition like below.
<?php

$posts = DB::table('posts')
    ->whereNotNull('published_at')
    ->get();

Inverse of whereNotNull


The inverse of "whereNotNull()" is "whereNull()" and this method will check if the value is NULL.
<?php

Post::query()
    ->whereNull('published_at')
    ->get();

DB::table('posts')
    ->whereNotNull('published_at')
    ->get();
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this