personally, I would probably create an accessor method on the model to return the truncated body, and then in the view {{ $model->shortBody }}
How to move Blade string manipulation logic into a Livewire component?
In my Livewire component, I'm displaying a list of articles, and currently, I'm truncating the body field in my Blade template like this:
<p>{{ Illuminate\Support\Str::of(strip_tags($article->body))->limit(300) }}</p>
However, I'd like to move this logic from the Blade template into the Livewire component so that the data is already processed when passed to the view.
Here's the simplified version of my Livewire component:
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Article as Model;
use Illuminate\Support\Str;
class Article extends Component
{
public function render()
{
return view('livewire.article', [
'articles' => Model::paginate(6),
]);
}
}
Question: What’s the best way to handle this kind of data manipulation in the Livewire component before sending it to the view? Should I process each article’s body field directly in the render() method, or is there a more efficient approach in Livewire?
Thanks for any guidance!
One more thing I forgot to mention, you can also use the str helper function instead of Str::of and importing Illuminate\Support\Str at the top, I think.
return Attribute::make(
get: fn (string $value, array $attributes) => str(strip_tags($attributes['body']))->limit(300),
);
Please or to participate in this conversation.