How to Word limit of a string in Laravel?

Spread the love

Hello Guys,

When it comes to managing Word limit of a string, you have a variety of options at your disposal. Whether you prefer CSS, JavaScript, or PHP, there are multiple techniques to achieve the desired results.

Additionally, for those working with Laravel, a convenient solution is available through the Str class within the Illuminate\Support\Str namespace. Let’s explore how this can simplify the task at hand.

Examples of Word limit of a string in laravel

Also Read: How can i the Get Last Record from Database in Laravel?

Limit string length in Blade

To effectively restrict the length of a string within your Blade files, you can employ the following technique:

    {{ Str::limit($your_string, 50) }}

You don’t need to explicitly declare the namespace because this is an inherent PHP function accessible globally within Laravel. Simply replace the “$your_string” placeholder with your specific string, and adjust the “50” value to specify the desired character limit for your string.

Limit string length in Model

Opting for the same technique within your Model directly, instead of repeating it in your views on every occasion:

Also Read: How to rename Git Branch Name with Git Command?

use Illuminate\Support\Str;

class Post
    const LIMIT = 50;

    protected $fillable = [
        ..., 'description'

    public function limit()
        return Str::limit($this->description, YourClass::LIMIT )

In your blade file, you can simply invoke this method:

    {{ $post->limit}}

Streamlining your content creation becomes more efficient when you define a single length parameter in one file and leverage it across various sections.

Limit string length in Controller

You can incorporate this logic into your controller. Therefore, prior to returning your view, it would appear as follows:

Also Read: How to Check Query Execution Time in Laravel 10?


namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Post;

class PostController extends Controller
    public function show($id)
        $post = Post::findOrFail($id);
        $post->description = Str::limit($post->description, 50);
        return view('', compact('post'));

Next, in your perspective, you simply have to perform the following:

Also Read: How to add Custom Validation Error Message in LARAVEL 10

    {{ $post->description }}

We trust you’ll discover our Laravel Blogs to be a valuable resource.

Leave a Comment