Laravel 10 How to Convert String to CamelCase in Laravel?

Hello Artisan, today I'll show you how to Convert String to CamelCase in Laravel  in our Laravel application. I'm going to demonstrate an example of using Laravel's str_camel function to convert a string to camelCase. The Str::camel() method in Laravel transforms a string with underscores, hyphens, or spaces into camel case by capitalizing the initial letter of each word, except for the first one. Here's an example:

In this example, Str::camel() transforms 'hello_world' into 'helloWorld' by replacing underscores with capitalized letters in the second word. let's see the simple example:

Table of Contents

  1. Install Laravel App
  2. Laravel String to CamelCase in Controller
  3. Output
  4. Laravel String Starts With in Blade File
  5. Output

Install Laravel App

Creating the Laravel app is not necessary for this step, but if you haven't done it yet, you can proceed by executing the following command

composer create-project laravel/laravel-camel

Laravel String to CamelCase in Controller

Using the Laravel framework's Str::camel() method to convert the string "hello_world" into "helloWorld" and then display the result using dd(). This code is correct and will work as expected to demonstrate the transformation. We can use it with controller like this way:

app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $string = "hello_world";
        $newString = Str::camel($string);

        dd($newString);
    }
}

Output:

"helloWorld" // app\Http\Controllers\UserController.php:20

Laravel String Starts With in Blade File

To convert a Laravel string to CamelCase in a Blade file, you can use the Str::camel() function provided by Laravel. Here's an example of how you can do this in a Blade file:

<p>{{ Str::camel('hello_world') }}</p>

Make sure that you have the use Illuminate\Support\Str; statement at the top of your Blade file or within your PHP code to use the Str::camel() function.

Output

helloWorld

That's it for today. I hope it'll be helpful in upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐Ÿ™‚