In this section, we will see how to find the length of a string in Laravel. You can use the Laravel helper method Str::length()
or the PHP strlen()
method to find the string length.
Let’s take a look at the following example to understand how it works.
Example 1
Str::length
method in laravel.
<?php
namespace App\Http\Controllers;
use App\Models\Blog;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class BlogController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$stringLength = Str::length('laravel best framework');
dd($stringLength);
}
}
Example 2
let see another example.
<?php
namespace App\Http\Controllers;
use App\Models\Blog;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class BlogController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$blog = Blog::find(1);
$blogLength = Str::length($blog->description);
dd($blogLength);
}
}
You can also find the string length using the strlen()
method, which is a built-in PHP function.
PHP strlen() method
<?php
namespace App\Http\Controllers;
use App\Models\Blog;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class BlogController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$stringLength = 'laravel best framework';
dd(strlen($stringLength));
}
}