Laravel Tutorials

Streamlining String Manipulation with Laravel's string() Method

Published
Streamlining String Manipulation with Laravel's string() Method image

Laravel's request->string() method transforms input into Stringable instances, providing fluent string manipulation capabilities through method chaining.

// Basic transformation
$name = $request->string('name')
->trim()
->title()
->limit(50);
 
// Input
$request->input('name') = ' jANE mARY smith ';
 
// Output after string() transformation
'Jane Mary Smith'

Here's an example of profile data sanitization:

<?php
 
namespace App\Http\Controllers;
 
use App\Models\Profile;
use Illuminate\Http\Request;
 
class ProfileController extends Controller
{
public function update(Request $request, Profile $profile)
{
$profile->update([
'display_name' => $request->string('name')
->trim()
->title()
->limit(50)
->toString(),
 
'username' => $request->string('username')
->trim()
->lower()
->replaceMatches('/[^a-z0-9_-]/', '')
->limit(20)
->toString(),
 
'bio' => $request->string('bio')
->trim()
->stripTags()
->limit(160)
->toString(),
 
'website' => $request->string('website')
->trim()
->lower()
->replace(['http://', 'https://'], '')
->before('/')
->toString()
]);
 
return response()->json([
'message' => 'Profile updated successfully',
'profile' => $profile->fresh()
]);
}
}

The string() method simplifies input sanitization and transformation through fluent method chaining, making string manipulation more readable and maintainable.

Harris Raftopoulos photo

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

Sponsored

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
PayZephyr: One Payment API for Stripe, Paystack, and PayPal image

PayZephyr: One Payment API for Stripe, Paystack, and PayPal

Read article
Bifrost Turns One With AI Builds and New Workflows image

Bifrost Turns One With AI Builds and New Workflows

Read article
Preview Blade Templates in macOS Finder with Quick Blade image

Preview Blade Templates in macOS Finder with Quick Blade

Read article
Artisan Debugging Commands in Laravel Telescope 5.24.0 image

Artisan Debugging Commands in Laravel Telescope 5.24.0

Read article
Queue totalSize() and JobInterrupted Event in Laravel 13.31 image

Queue totalSize() and JobInterrupted Event in Laravel 13.31

Read article
Find Unexpected Test Inputs with Fuzz for Pest image

Find Unexpected Test Inputs with Fuzz for Pest

Read article