How to Get Length of String in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Hi Artisan,

In this profound tutorial, we will learn how to get length of string in laravel. let’s discuss about length of string laravel. This post will give you a simple example of laravel get string length. if you want to see an example of laravel string length example then you are in the right place. So, let us see in detail an example.

In Laravel, you can use the Str::length method to get the length of a string.

Here's how you can use it:

1. First, make sure you have the Str facade imported at the top of your file:

2. Then, you can use the Str::length method to get the length of a string:

In the example above, the Str::length method takes a string as its parameter and returns the length of the string. In this case, the value of $length will be 14, as the string "Hello, Hardik!" has 14 characters including spaces and punctuation marks.

let's see the simple example:

Laravel Get String Length in Controller

you can use it with controller like this way:

Controller Code:

<?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, Hardik!";

$length = Str::length($string);

dd($length);

}

}

Output:

14

Laravel Get String Length in Blade File

you can use it with blade file like this way:

Blade File Code:

<p>{{ Str::length('Hello, Hardik!') }}</p>

Output:

14

I hope it can help you...

Tags :
Shares