'Laravel implode array items to new lines

Here is my array from hasMany relationship in Laravel framework.

$array = ['php','css','hrml'];

How can I display as below using implode function. (code in my view is {{ $photo->tags->pluck('tag')->implode(",\n") }})

Expected out put:

php,

css,

html

Should be on the next line



Solution 1:[1]

Displaying Unescaped Data

You can use <br> in the implode function and By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax {!! !!}:

{!! $photo->tags->pluck('tag')->implode(",<br>") !!}

Output:

php,
css,
html

Solution 2:[2]

You can also try like this,

$tag = ['php','css','hrml'];

echo implode("<br />" ,$tag);

Solution 3:[3]

The more secure way to handle this in Blade:

@foreach ($photo->tags->pluck('tag') as $tag)
    {{ $tag }} {{ $loop->last ? '' : '<br>' }}
@endforeach

Yes, this is not a single line solution, but it does make your application more secure.

When rendering a variable with {!! $variable !!} it is not escaped and thus is a potential security risk when the variable contains user supplied data. Any (malicious) html from the user would then be executed. It is better to resolve this the secure way by default. Only use the {!! $variable !!} syntax when you are sure that the data in the variable is safe to be displayed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Vasu Kuncham
Solution 3 Robin Bastiaan