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.
Here is what you can use to print the tag names in your blade template
{{$post->tags->implode('name',', ')}}
Simple! Isn't it.
Comments