Hidden Methods Beginner Since Laravel 11.x

Str::chopStart() & chopEnd()

Remove a specific prefix or suffix from a string only if it is present — no regex, no conditionals.

Overview

Str::chopStart() removes a given prefix from the start of a string (if present). Str::chopEnd() does the same for a suffix. Unlike ltrim()/rtrim(), these methods match the exact string, not individual characters.

Usage

use Illuminate\Support\Str;

Str::chopStart('https://laravel.com', 'https://');
// 'laravel.com'

Str::chopEnd('photo.jpg', '.jpg');
// 'photo'

// Only removes if it matches — safe to call even if the prefix isn't there
Str::chopStart('laravel.com', 'https://');
// 'laravel.com' (unchanged)

Works on the fluent Stringable too:

str('app/Models/User.php')
    ->chopStart('app/')
    ->chopEnd('.php')
    ->replace('/', '\\')
    ->toString();
// 'Models\User'

Comparison with trim

rtrim('photo.jpg', '.jpg') would remove any combination of the characters ., j, p, g from the end — potentially eating into the filename. chopEnd() only removes the exact suffix:

rtrim('setting.jpg', '.jpg');
// 'settin' — oops!

Str::chopEnd('setting.jpg', '.jpg');
// 'setting' — correct!

When to Use

  • Stripping known URL prefixes (http://, https://)
  • Removing file extensions safely
  • Cleaning up path prefixes or suffixes
  • Any time you'd use str_starts_with() + substr() together