list separated by comma, but the last item must not have a comma

In laravel how do i separate each category with a comma, if there are many categories, the last item shouldnt have comma. . .

it should look like:

Job categories: category1, category2, category3, category4

Here is my code:

@if(count($job->categories) < 2)
     @foreach($job->categories as $category)
         {{ $category->name }}
     @foreach($job->categories as $category)
         {{ $category->name . ", " }}


Try this:

implode(',', array_map(function($a){return $a['name'];}, $job->categories->toArray()))

You want all the names in an array, in order to implode them with a comma. So you iterate the categories with array_map. But array_map needs an array, not a Collection, so you first need to convert the categories Collection into an array with its toArray function.

But I think @CorradoStriuli answer is far more elegant and 'laravelish'.

You can use the method 'lists' from Collection class. More info at: Illuminate\Database\Eloquent\Collection

{{ implode(', ', $job->categories->lists('name')) }}

Assuming categories is a Collection you can do that easily

{{ $job->categories->implode('name', ', ') }}

There is a lot of way you could do that :

For example :

using substr() :

$yourString = susbtr($yourString,0,strlen($yourString-1));

using trim() :

$yourString = trim($yourString,',');

Assuming $job->categories is an array (and not something Iteratable), you could just use implode:

$yourString = implode(",",$job->categories);
//$yourString now contains a comma seperated list of categories

Or, doing it inside a twig template you can use join I believe (been a while since I used twig...)

{{ $job->categories|join(',') }}

Need Your Help

Variable grouping providing different answers in optimized code

c++ gcc optimization floating-point floating-accuracy

I've been attempting to unit test a C++ class I've written for Geodetic transforms.

javascript: receive radio button value in a radio group and command different instruction according to each case

java javascript html jsp

I want to store new row in a database table when a person checked a first radio button in a radio group. Inserting database row is ok. But I don't know a below part among the whole codes.