comma separated print using Implode on many to many relationship in Laravel

Laravel collection has a useful method that you can use on collection to combine the items of the collection together.

This implode function provided in Laravel Collection works a bit differently than the implode function available in php. Using implode on laravel collection can work on a collection of arrays and objects.


//Collection of string
$collection = collect(["one", "two", "three"]);

// one-two-three
$imploded = $collection->implode('-');

Similarly, if you are looking to echo out the comma separated values of your many to many relationships in Laravel.

Let’s say you have a Post model having many to many relationships with Tag model.

Livewire Component Library

Here is what you can use to print the tag names in your blade template

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.
{{$post->tags->implode('name',', ')}}

Simple! Isn’t it.

Site Footer