Inside this article we will see the concept i.e Laravel 9 How To Limit The Length of a String Example Tutorial. Article contains the classified information about laravel limiting string length inside blade template.
If you are looking for a solution i.e How to Truncate String in Laravel then this article will help you a lot for this. Tutorial is super easy to understand and implement it in your code as well.
Read More: Laravel 9 How to Set Timezone Example Tutorial
We will see the concept of limiting a string in blade files, controller, model of laravel. You will get entire concept to truncate a string value to a specific length.
Let’s get started.
Laravel Installation
Open terminal and run this command to create a laravel project.
composer create-project laravel/laravel myblog
It will create a project folder with name myblog inside your local system.
To start the development server of laravel –
php artisan serve
URL: http://127.0.0.1:8000
Assuming laravel already installed inside your system.
Example #1 Limit String Length in Controller
Let’s consider a laravel controller. We will understand the concept truncating a string value with this.
Before returning to blade template code would look like this:
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Product; class ProductController extends Controller { public function show($id) { $product = User::findOrFail($id); $product->description = Str::limit($product->description, 50); return view('user.profile', compact('product')); } }
Read More: PHP How to Convert Camel Case to Snake Case Tutorial
Then in your view you would just need to do:
<p>
{{ $product->description }}
</p>
Example #2 Limit String Length in Model
Let’s consider a laravel model. We will understand the concept truncating a string value with this.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class Product extends Model { use HasFactory; const LIMIT = 50; protected $fillable = [ //... 'description' ]; public function limit() { return Str::limit($this->description, Item::LIMIT); } }
Then in your blade template you would just need to call this method:
<p>
{{ $product->limit}}
</p>
Example #3 Limit String Length in Blade Template
Let’s consider a laravel blade template. We will understand the concept truncating a string value with this.
<p>
{{ Str::limit($your_string, 50) }}
</p>
Just change the $your_string
part with your actual string and also the 50
part with the number of characters that you would like to limit your string to.
Read More: 5 Best Ways to Convert PNG to SVG Example Tutorial
We hope this article helped you to learn Laravel 9 How To Limit The Length of a String Example Tutorial in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.