Laravel Image

In this tutorial, you’ll learn how to convert a string to CamelCase in Laravel using both a controller method and a Blade template.

Part 1: Converting String to CamelCase in Laravel Controller

Step1: Create a New Controller

  1. Open your Laravel project’s terminal.
  2. Use the php artisan make:controller command to create a new controller. For instance, create a “CamelCaseController”:
php artisan make:controller CamelCaseController

Step2: Implement CamelCase Conversion

  1. Open the newly created CamelCaseController.php file in the app/Http/Controllers directory.
  2. In a controller method, use the Str::studly() function to convert a string to CamelCase:
use Illuminate\Support\Str;

// ...

public function toCamelCase($inputString)
{
    $camelCaseString = Str::studly($inputString);
    return view('camel-case', ['inputString' => $inputString, 'camelCaseString' => $camelCaseString]);
}

Step3: Define Route

  1. Open the routes/web.php file.
  2. Define a route that uses the toCamelCase method in the CamelCaseController:
Route::get('/camel-case/{input}', 'CamelCaseController@toCamelCase');

Part 2: Displaying CamelCase String in Laravel Blade Template

Step1: Create a Blade View

  1. Navigate to your Laravel project’s resources/views directory.
  2. Create a new Blade view file. For instance, name it “camel-case.blade.php”.

Step2: Display CamelCase String in Blade Template

  1. Open the “camel-case.blade.php” file.
  2. Inside the Blade template, display the CamelCase string passed from the controller:
<!DOCTYPE html>
<html>
<head>
    <title>String to CamelCase Conversion</title>
</head>
<body>
    <p>Original String: {{ $inputString }}</p>
    <p>CamelCase String: {{ Str::studly($inputString) }}</p>
</body>
</html>

Conclusion

Congratulations! You’ve successfully learned how to convert a string to CamelCase in Laravel using both a controller method and a Blade template. This technique can be applied to transform strings for various purposes in your Laravel application.

Feel free to explore further and use this method wherever you need to convert strings to CamelCase. Happy coding!

Read More

1 thought on “Convert String to CamelCase in Laravel

Comments are closed.