Stop Missing New Laravel Features. Join 1,400+ Devs Getting Alerts. Sign Up Free →

Check for null AND empty string in Laravel (or just PHP, really)

Not published • 2 minutes read time

Checking for null and empty strings, particularly when you're dealing with the database, is a good idea.

Here's how to check for an empty value (either null, or an empty string) in PHP, with a look at a Laravel helper function that makes this cleaner and easier to implement.

As a real-world example, I recently implemented social authentication with the ability to have no password set for users. I won't get into the specifics, but I had a method on my User model like this:

public function hasPassword(): bool
{
    return ! is_null($this->password);
}

Seems ok, until you realize that this breaks down if the password column is an empty string (for whatever reason).

To safely check for a null and empty string value, do this instead:

public function hasPassword(): bool
{
    return ! is_null($this->password) && $this->password !== '';
}

Of course, tweak the logic depending on how you prefer to write these conditionals. But, we can now safely check if the password is just...empty either way.

I verified this functionality with a couple of unit tests for the User.

it('returns if a user does not have a password', function () {
    $user = new User;

    $user->setRawAttributes([
        'password' => null,
    ]);

    expect($user->hasPassword())->toBeFalse();
});

it('returns if a user does not have a password (empty string)', function () {
    $user = new User;

    $user->setRawAttributes([
        'password' => '',
    ]);

    expect($user->hasPassword())->toBeFalse();
});

If you want to be super clean about this, there's also the filled Laravel helper function. This replaces the need to use is_null and compare to ''.

public function hasPassword(): bool
{
    return filled($this->password);
}

Both my unit tests still pass, and I prefer this cleaner syntax... so we're sticking with that!

So, it's pretty important to not only check for null values, particularly with your database columns, but also empty strings. I've shown you a couple of ways to do this here, with both being completely valid depending on your preference.

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!

Tagged under