1

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

Bira
  • 4,531
  • 2
  • 27
  • 42

3 Answers3

6

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

Inzamam Idrees
  • 1,955
  • 14
  • 28
  • `Desert,
    Nature,
    Natural environment,
    Sand,
    Sky,
    Natural landscape,
    death valley landscape` - not working
    – Bira Mar 22 '19 at 06:38
  • 1
    @Bira instead of `{{ }}` use `{!! !!}` – Inzamam Idrees Mar 22 '19 at 06:42
  • Please explain your answer, it will be helpful to others. – Bira Mar 22 '19 at 06:45
  • Does this solution not bring a security risk? I would like to display the
    as html, without enabling the posibility for html in the variable to be executed.
    – Robin Bastiaan Apr 26 '22 at 09:12
  • @RobinBastiaan This is not a security risk. Because we use this `{!! !!}` for rendering the html and this is the functionality of Laravel blade. – Inzamam Idrees Apr 28 '22 at 06:37
  • @InzamamIdrees When rendering a variable with `{!! !!}` it is not escaped and thus is a potential security risk when the variable contains user supplied data. Any (malicious) html from the user will then be executed. – Robin Bastiaan Apr 28 '22 at 07:52
  • @RobinBastiaan then this is the exceptional case, for this we handle the exceptions from controller maybe – Inzamam Idrees Apr 28 '22 at 08:39
0

You can also try like this,

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

echo implode("<br />" ,$tag);
Vasu Kuncham
  • 528
  • 3
  • 14
0

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.

Robin Bastiaan
  • 572
  • 2
  • 8
  • 21