string limit in laravel

How to limit the length of a string in Blade file Laravel ?

In this tutorial, I will give you an example of the “How to limit the length of a string in Blade file in Laravel“, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

We have a blade file in laravel application, where we have a name, email, and address fields.

We listed all the table data in the blade file using foreach loop, The address field string is more than the limit to show correctly in the blade file, so we use the PHP function (mb_strimwidth) to show the address field in the correct way, we set the string limit in list blade file, and you can see the complete address field data using the primary id in view or edit blade files in the application.

Preview: Before string limit :

string limit in blade file in laravel

Preview: After string limit :

set the string limit in laravel

routes\web.php

 Route::get('/string-limit-example','TestController@strlimit');

routes\weApp\Http\Controllers\TestController

 <?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;
 use App\Model\TestTable1;
 use App\StudentDetail;

 class TestController extends Controller
 {

  public function strlimit(){
    $data = TestTable1::all();
    return view('strlimitexample',compact('data'));
  }
 }

resources\views\strlimitexample.blade.php

       <div class="container">
         <h3>String Limit Example in Laravel</h3>
         <table class="table">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Name</th>
                  <th>Email</th>
                  <th>Address</th>
               </tr>
            </thead>
            <tbody>
             @foreach($data as $key => $data)
              <tr>
               <td>{{ $key+1 }}</td>
               <td>{{$data->name}}</td>
               <td>{{$data->email}}</td>
               <td>{!!mb_strimwidth(($data->address),0,50,'.....')!!}
               </td>
              </tr>
            </tbody>
            @endforeach
         </table>
      </div>

Now, you can see the output in the blade file, we have successfully implemented the string limit in the address field.

str limit in laravel

In this article, we learned “Limit the length of a string in Blade file Laravel”, I hope this article will help you with your application Project.

Also Read: Increment letters like numbers in Laravel.