Search code examples
laravellaravel-5laravel-5.4laravel-collection

How to get names from collection Laravel?


In template Laravel I need to show name field from collection:

[{"announcement_id":2,"name":"Name1","amount":1},{"announcement_id":2,"name":"Name2","amount":2}]

About I want to get the following:

<h2>Name1 / Name 2</h2>

Solution

  • In fact you can use collection pluck method together with implode method, so having collection like this:

    $c = collect([
        (object)["announcement_id" => 2, "name" => "Name1", "amount" => 1],
        (object)["announcement_id" => 2, "name" => "Name2", "amount" => 2],
    ]);
    

    to get the text you want you can use:

    echo '<h2>' .($c->pluck('name')->implode(' / ')).'</h2>';
    

    EDIT

    As pointed by @Samsquanch in comment you can even use only implode like this:

    echo '<h2>' .($c->implode('name', ' / ')).'</h2>';