Laravel Tutorials

Checking String Absence with Laravel's doesntContain

Published
Checking String Absence with Laravel's doesntContain image

Laravel's new doesntContain method provides a more intuitive way to check if strings lack certain content. This method complements the existing contains method, offering a cleaner syntax for negative checks.

use Illuminate\Support\Str;

// Basic usage
$text = "Welcome to Laravel";
$result = Str::doesntContain($text, 'PHP'); // true
// Multiple checks
$result = Str::doesntContain($text, ['PHP', 'Laravel']); // false

Here's a practical example of implementing a message filtering service:

<?php

namespace App\Services;

use App\Models\Message;
use Illuminate\Support\Str;

class MessageFilter
{
    protected array $sensitiveTerms = [
        'confidential',
        'internal',
        'classified'
    ];

    public function isSafeForPublic(Message $message): bool
    {
        return Str::doesntContain(
            strtolower($message->content),
            $this->sensitiveTerms
        );
    }

    public function processMessage(Message $message): array
    {
        if ($this->isSafeForPublic($message)) {
            $message->update(['status' => 'published']);
            return ['status' => 'success', 'message' => 'Message published'];
        }
        $message->update(['status' => 'review_required']);

        return ['status' => 'pending', 'message' => 'Content needs review'];
    }
}

The doesntContain method streamlines string validation in Laravel applications, providing a more intuitive syntax for checking the absence of specific content. Whether you're building content moderation systems, input validation, or data filtering, this method reduces complexity and improves code readability. Combined with Laravel's other string helpers, it forms part of a comprehensive toolkit for efficient string manipulation.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Generate Laravel Validation Rules From a JSON Schema image

Generate Laravel Validation Rules From a JSON Schema

Read article
Laravel Suspicious Login: Detect and Block Risky Logins image

Laravel Suspicious Login: Detect and Block Risky Logins

Read article
Decide with Jev: Make Failed AI Requests Safe in Laravel image

Decide with Jev: Make Failed AI Requests Safe in Laravel

Read article
Black Friday: Learn the habits behind AI workflows that work image

Black Friday: Learn the habits behind AI workflows that work

Read article
Laravel Black Friday and Cyber Monday Deals 2026 image

Laravel Black Friday and Cyber Monday Deals 2026

Read article
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article