Home >Backend Development >PHP Tutorial >Streamlining String Manipulation with Laravel's string() Method
Laravel's request->string()
method offers a streamlined approach to string manipulation. It converts input data into Stringable objects, enabling fluent method chaining for efficient transformations.
This example demonstrates basic usage:
// Basic transformation $name = $request->string('name') ->trim() ->title() ->limit(50); // Input: $request->input('name') = ' jANE mARY smith '; // Output: 'Jane Mary Smith'
Here's a practical application in 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 enhances code readability and maintainability by simplifying input sanitization and transformation through chained method calls, making string manipulation cleaner and more efficient.
The above is the detailed content of Streamlining String Manipulation with Laravel's string() Method. For more information, please follow other related articles on the PHP Chinese website!