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 theStr::of()
method. All fluent string methods can be found in the official documentation. - In Laravel 9, they added a new
str()
helper. Thestr()
function is shorter and equivalent to theStr::of()
method, which returns theIlluminate\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...