Posts Learn Components new Snippets new Categories Tags About
/

How to Query Column That is Not Null In Laravel

Learn how to query a column that's NOT NULL in Laravel the easy way. Make use of this query directive to get the result as necessary.

Created on Oct 08, 2021

30 views

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();
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻