DEV Community

Ankit Verma
Ankit Verma

Posted on

1

Effortless String Manipulation with Laravel's string() Method

Laravel’s $request->string() method converts input into a Stringable instance, enabling fluent string manipulation through method chaining. This makes input sanitization and transformation more intuitive and maintainable.

Basic Transformation Example

$name = $request->string('name')
    ->trim()
    ->title()
    ->limit(50);
Enter fullscreen mode Exit fullscreen mode

Input:

$request->input('name') = '  jANE mARY smith   ';
Enter fullscreen mode Exit fullscreen mode

Output:

'Jane Mary Smith'
Enter fullscreen mode Exit fullscreen mode

Sanitizing Profile Data
The following example demonstrates how to clean and format user profile data before updating the database:


<?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()
        ]);
    }
}

Enter fullscreen mode Exit fullscreen mode

Why Use string()?
The $request->string() method streamlines input handling by allowing chained transformations, improving both readability and efficiency. Whether you're formatting names, cleaning usernames, or sanitizing text input, this method ensures clean and structured data with minimal effort.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs