Laravel String Helpers: 16 Open-Source Examples

Laravel String Helpers: 16 Open-Source Examples
Admin
Tuesday, November 14, 2023 7 mins to read
Share
Laravel String Helpers: 16 Open-Source Examples

Laravel has a lot of valuable helper functions. This post will show 16 examples of string helpers and how they are used in real projects.


Notice: String Syntax Changes

Before we begin, a little notice: you may find different variants of the same String functions, so you would understand the differences, here's what were added in Laravel lately.

  • In Laravel 7, they added Fluent String Operations. You may create a fluent Illuminate\Support\Stringable object using the Str::of() method. All fluent string methods can be found in the official documentation.
  • In Laravel 9, they added a new str() helper. The str() function is shorter and equivalent to the Str::of() method, which returns the Illuminate\Support\Stringable.

1. Str::slug()

The easiest way to create a slug from a given string without using any external packages is the Str::slug() helper.

An example is from an open-source platform BookStackApp.

use Illuminate\Support\Str;
 
class ImageStorage
{
// ...
 
public function cleanImageFileName(string $name): string
{
$name = str_replace(' ', '-', $name);
$nameParts = explode('.', $name);
$extension = array_pop($nameParts);
$name = implode('-', $nameParts);
$name = Str::slug($name);
 
if (strlen($name) === 0) {
$name = Str::random(10);
}
 
return $name . '.' . $extension;
}
 
// ...
}

Link to the example in GitHub repository.


2. Str::title()

Create a title from a string where the first letter of every word starts with a capital letter using Str::title() helper.

An example is from an open-source platform BookStackApp.

// ...
<h1 class="list-heading">{{ Str::title(trans('auth.log_in')) }}</h1>
// ...

Link to the example in GitHub repository.


3. Str::startsWith()

If you need to check whether a string starts with a given value, the Str::startsWith() helper is just for that.

An example is from an open-source project Pterodactyl.

use Illuminate\Support\Str;
 
class ActivityLogged extends Event
{
// ...
 
public function isServerEvent(): bool
{
return Str::startsWith($this->model->event, 'server:');
}
 
// ...
}

Link to the example in GitHub repository.


4. Str::endsWith()

Opposite to the Str::startsWith(), the Str::endsWith() helper checks if a given string end with a provided value.

An example is from an open-source project creater.

use Illuminate\Support\Str;
 
class PathToZip implements Rule
{
// ...
 
public function passes($attribute, $value)
{
return Str::endsWith($value, '.zip');
}
 
// ...
}

Link to the example in GitHub repository.


5. Str::before() and basename()

The Str::before() helper returns everything from a string before a given value.

An example is from an open-source project creater. The basename will return a full filename with an extension, and from the Str::before, everything before .blade.php will be returned.

use Illuminate\Support\Str;
 
class Invoice extends Model implements HasMedia
{
// ...
 
public static function invoiceTemplates()
{
$templates = Storage::disk('views')->files('/app/pdf/invoice');
$invoiceTemplates = [];
 
foreach ($templates as $key => $template) {
$templateName = Str::before(basename($template), '.blade.php');
$invoiceTemplates[$key]['name'] = $templateName;
$invoiceTemplates[$key]['path'] = vite_asset('img/PDF/'.$templateName.'.png');
}
 
return $invoiceTemplates;
}
 
// ...
}

Link to the example in GitHub repository.


6. Str::kebab()

The Str::kebab() helper converts a string to a kebab-case.

An example is from an open-source project akaunting.

use Illuminate\Support\Str;
 
trait Sources
{
// ...
 
public function getSourceAlias()
{
$prefix = '';
 
$namespaces = explode('\\', get_class($this));
 
if (empty($namespaces[0]) || (empty($namespaces[1]))) {
return $prefix;
}
 
if ($namespaces[0] != 'Modules') {
return 'core';
}
 
$prefix = Str::kebab($namespaces[1]);
 
return $prefix;
}
}

Link to the example in GitHub repository.


7. Str::snake()

The Str::snake() helper converts a string to a snake_case.

An example is from an open-source project akaunting.

use Illuminate\Support\Str;
 
abstract class Export implements FromCollection, HasLocalePreference, ShouldAutoSize, ShouldQueue, WithHeadings, WithMapping, WithTitle, WithStrictNullComparison
{
// ...
 
public function title(): string
{
return Str::snake((new \ReflectionClass($this))->getShortName());
}
 
// ...
}

Link to the example in GitHub repository.


8. Str::plural()

The Str::plural() helper is a handy method for converting a singular word to its plural form.

An example is from an open-source project laravel.io.

// ...
<span class="text-gray-700">
{{ $member->solutions_count }} {{ Str::plural('Solution', $member->solutions_count) }}
</span>
// ...

Link to the example in GitHub repository.


9. Str::random()

A handy helper Str::random() to generate a random string with a specified length.

An example is from an open-source page freek.dev.

use Illuminate\Support\Str;
 
class Post extends Model implements Feedable, HasMedia, Sluggable
{
// ...
 
public static function booted()
{
static::creating(function (Post $post) {
$post->preview_secret = Str::random(10);
});
 
// ...
}
 
// ...
}

Link to the example in GitHub repository.


10. Str::of()->contains()

An example of a fluent string syntax with a contains() helper to check if a string contains a given value.

An example is from an open-source project pixelfed.

use Illuminate\Support\Str;
 
class AutolinkService
{
const CACHE_KEY = 'pf:services:autolink:';
 
public static function mentionedUsernameExists($username)
{
$key = 'pf:services:autolink:userexists:' . hash('sha256', $username);
 
return Cache::remember($key, 3600, function() use($username) {
$remote = Str::of($username)->contains('@');
$profile = Profile::whereUsername($username)->first();
// ...
});
}
}

Link to the example in GitHub repository.


11. Str::of()->explode()->last()

An example of a fluent string syntax where a string is using explode() method is exploded by a given delimiter. The explode() returns a collection to which the last() method is used to receive only the last item as a result.

An example is from an open-source project pixelfed.

use Illuminate\Support\Str;
 
class AvatarService
{
// ...
 
public static function cleanup($avatar, $confirm = false)
{
// ...
 
$curFile = Str::of($avatar->cdn_url)->explode('/')->last();
 
$files = $files->filter(function($f) use($curFile) {
return !$curFile || !str_ends_with($f, $curFile);
})->each(function($name) use($disk) {
$disk->delete($name);
});
 
return;
}
}

Link to the example in GitHub repository.


12. Str::limit()

The [Str::limit()] is helpful to create, for example, excerpts from a string by a given length.

An example is from an open-source project laravel.io.

use Illuminate\Support\Str;
 
final class Reply extends Model implements MentionAble, Spam
{
// ...
 
public function excerpt(int $limit = 100): string
{
return Str::limit(strip_tags(md_to_html($this->body())), $limit);
}
 
// ...
}

Link to the example in GitHub repository.

Another example is from an open-source page freek.dev.

use Illuminate\Support\Str;
 
class Ad extends Model
{
// ...
 
public function getExcerptAttribute()
{
return Str::limit($this->text);
}
}

Link to the example in GitHub repository.


13. Str::replaceLast()

The Str::replaceLast replaces the last provided value in a string with a given new value.

An example is from an open-source page spatie.be.

use Illuminate\Support\Str;
 
class DisplayablePrice
{
// ...
 
public function formattedPrice(): string
{
$amount = number_format($this->priceInCents / 100, 2, '.', ' ');
 
$amount = Str::replaceLast('.00', '', $amount);
 
return "{$this->currencySymbol} {$amount}";
}
}

Link to the example in GitHub repository.


14. Str::of()->after()->before()->toString()

An example of a fluent string syntax where after(), before, and toString() methods are chained.

An example is from an open-source page spatie.be.

use Illuminate\Support\Str;
 
class MusicController
{
public function __invoke(): View
{
$playlists = Playlist::query()->get()->sortByDesc(
// Take number from "#123: The Playlist Title"
fn (Playlist $playlist) => (int) Str::of($playlist->name)
->after('#')
->before(':')
->toString()
);
 
return view('front.pages.blog.music', ['playlists' => $playlists]);
}
}

Link to the example in GitHub repository.


15. str()->camel()->kebab()

An example of a str() helper usage with camel and kebab methods chained.

An example is from an open-source package filament/tables.

// ...
 
<x-filament-tables::cell
:wire:key="$this->getId() . '.table.record.' . $recordKey . '.column.' . $column->getName()"
:attributes="
\Filament\Support\prepare_inherited_attributes($column->getExtraCellAttributeBag())
->class([
'fi-table-cell-' . str($column->getName())->camel()->kebab(),
$getHiddenClasses($column),
])
"
>
// ...

Link to the example in GitHub repository.


16. str()->before()->kebab()->replace()->ucfirst()

An example of a str() helper usage with before, kebab, replace, and ucfirst methods chained to generate a label.

An example is from an open-source package filament/forms.

class Select extends Field implements Contracts\HasAffixActions, Contracts\HasNestedRecursiveValidationRules
{
// ...
 
public function getLabel(): string | Htmlable | null
{
if ($this->label === null && $this->hasRelationship()) {
$label = (string) str($this->getRelationshipName())
->before('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
 
return ($this->shouldTranslateLabel) ? __($label) : $label;
}
 
return parent::getLabel();
}
 
// ...
}

Link to the example in GitHub repository.