'how to prevent html encoding(special chars) in laravel?
I have saved some html code in a my database ( using laravel 5.7 , Sqlite ) it saved but after that i want to show it , laravel encodes the special chars.
it have to return as a JSON string to angular without any encoding or changes.
I just want to prevent html special chars encoding.
I have tried this :
$post = Post::find($id);
$content = html_entity_decode($post->content);
return ['content' => $content ];
But it doesn't work
Solution 1:[1]
in your controller
1 $post = Post::find($id);
2 $content =$post->content;
3 return redirect('/your-url')->with(['content'=>$content);
to return json
3. return response()->json($content);
in your blade file (please make sure that your file is saved with file-name.blade.php) you can just output content like thus
{!! $content !!}
Solution 2:[2]
Finally i tried this :
$post = new Post ;
...
$post->content = htmlspecialchars($request->content) ;
$post->save() ;
And then , I used htmlspecialchars_decode() for decoding post's content :
$post = Post::find($request->id) ;
$content = htmlspecialchars_decode($post->content);
return response()->json(['title'=>$post->title , 'content'=> $content]);
It works. Thanks for helping ...
Solution 3:[3]
Simply use built-in e(...) helper-function, like:
$myPlainText = e($myUserInput);
It probably has the smallest name I have ever seen, but does far more than htmlspecialchars(...) function, see:
if (! function_exists('e')) {
/**
* Encode HTML special characters in a string.
*
* @param \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|string $value
* @param bool $doubleEncode
* @return string
*/
function e($value, $doubleEncode = true)
{
if ($value instanceof DeferringDisplayableValue) {
$value = $value->resolveDisplayableValue();
}
if ($value instanceof Htmlable) {
return $value->toHtml();
}
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', $doubleEncode);
}
}
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 | Ali Reza |
| Solution 3 | Top-Master |
