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, 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Convert Image to Base64 in Laravel?
- How to Call Controller Function in Blade Laravel?
- Laravel Blade @includeWhen and @includeUnless Example
- Laravel Blade Include File If Exists Example
- Laravel Include Blade File with Data Example
- Laravel Blade Empty Directive Example
- Laravel 8 Clear Cache of Route, View, Config Command Example
- How to Write PHP Code in Laravel Blade?
- Laravel - How to Check If Array is Empty in Blade?
- Laravel - How to Get .env Variable in Blade or Controller?
- Laravel Ajax Render View With Data Example
- Laravel Blade Check if View Exists or Not Example