ItSolutionStuff.com

How to Truncate String in Laravel?

By Hardik Savani β€’ April 16, 2024
Laravel

Hi Guys,

Now, let's see a tutorial of how to truncate string in laravel. I explained simply step by step laravel limit string length. Here you will learn how to cut string in laravel. you can see laravel blade limit string length. Alright, let’s dive into the steps.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Laravel provide string helper using Str facade. we can set limit string length in blade file or controller file using Str::limit() function.

So, let's see the below examples:

Example 1: Laravel Limit string length in Blade File

resources/views/posts.blade.php

<!DOCTYPE html>

<html>

<head>

<title>How to Truncate String in Laravel? - ItSolutionStuff.com</title>

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>

<div class="container">

<h1>How to Truncate String in Laravel? - ItSolutionStuff.com</h1>

<table class="table table-bordered data-table">

<thead>

<tr>

<th>ID</th>

<th>Title</th>

<th>Body</th>

</tr>

</thead>

<tbody>

@foreach($posts as $post)

<tr>

<td>{{ $post->id }}</td>

<td>{{ $post->title }}</td>

<td>{{ Str::limit($post->body, 50) }}</td>

</tr>

@endforeach

</tbody>

</table>

</div>

</body>

</html>

Output:

Example 2: Laravel Limit string length in Controller File

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

use Illuminate\Support\Str;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$post = Post::first();

$body = Str::limit($post->body, 50);

return view('posts', compact('post'));

}

}

I hope it can help you...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

How to Convert Image to Base64 in Laravel?

Read Now β†’
β˜…

How to Call Controller Function in Blade Laravel?

Read Now β†’
β˜…

Laravel Blade @includeWhen and @includeUnless Example

Read Now β†’
β˜…

Laravel Blade Include File If Exists Example

Read Now β†’
β˜…

Laravel Include Blade File with Data Example

Read Now β†’
β˜…

Laravel Blade Empty Directive Example

Read Now β†’
β˜…

Laravel 8 Clear Cache of Route, View, Config Command Example

Read Now β†’
β˜…

How to Write PHP Code in Laravel Blade?

Read Now β†’
β˜…

Laravel - How to Check If Array is Empty in Blade?

Read Now β†’
β˜…

Laravel - How to Get .env Variable in Blade or Controller?

Read Now β†’
β˜…

Laravel Ajax Render View With Data Example

Read Now β†’
β˜…

Laravel Blade Check if View Exists or Not Example

Read Now β†’