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

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article
PIE 1.5 Changes PHP Extension Installs in CI image

PIE 1.5 Changes PHP Extension Installs in CI

Read article
Delete Expired Sessions in Laravel With a Scheduled Command image

Delete Expired Sessions in Laravel With a Scheduled Command

Read article
Pollora: Run WordPress Inside a Laravel Application image

Pollora: Run WordPress Inside a Laravel Application

Read article
Scheduled Session Garbage Collection in Laravel 13.39 image

Scheduled Session Garbage Collection in Laravel 13.39

Read article