How to Truncate String in 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 and laravel 9 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:

How to Truncate String in Laravel?

Example 2: Laravel Limit string length in Controller File

app/Http/Controllers/PostController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

use IlluminateSupportStr;

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…

Leave a Comment