Create an accessor in your Post model for it.
https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello,
Help me clean up the code? Need to call the function which has to be written separately, not in the Eloquent query.
I need to make a transform on the pagination object (apparently it can be done with through() method) in order to get the preview text for my list of Posts with some clean-up to the source text.
What I want is to put the function name in the query, not the function itself.
How do I write it separately and how do I call this function from query? I'm a bit confused with using $this-> on collection elements
This is my code:
use App\Http\Controllers\Controller;
use App\Models\Platforms;
use App\Models\Post;
use Illuminate\Support\Str;
public function index () {
$items = Post::where('platform_id', 1)
->with('category')
->with('platform')
->paginate(20)
->through(function ($item, $shorty = '') {
if (!empty($item->body)) {
$shorty = $item->body;
} elseif (!empty($item->body_short)) {
$shorty = $item->body_short;
}
$healthy = array(PHP_EOL, '!', '.', '?', ':');
$yummy = array(" ", "! ", ". ", '?', ': ');
$item->previewText = Str::words(
strip_tags(
str_replace($healthy, $yummy, $shorty)
),
35);
return $item;
});
return view('platforms.index', compact('items'));
}
}
Create an accessor in your Post model for it.
https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor
Please or to participate in this conversation.