Share this:

Today we are going to learn How to Truncate String in Laravel? This tutorial will cover on truncating string in laravel 9 application with examples.

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.

Example on How to Truncate String in Laravel?

  • Example 1: Laravel Limit string length in Blade File
  • Example 2: Laravel Limit string length in Controller File
  • Conclusion

Also Read: How to Integrating AdminLTE 3 in Laravel 9?

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? - LaravelTuts.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? - LaravelTuts.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
How to Truncate String in Laravel

Also Read: Laravel 9 Custom Login and Registration Example

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'));
    }
}

Also Read: How to Get Browser Name and Version in Laravel 9?

Conclusion

Today, We had learn How to Truncate String in Laravel?. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: How to Convert Image to Base64 in Laravel?

Share this:

Categorized in: