Laravel刀片逃生jQuery

In my laravel 4 project users can submit textarea data. I know I can escape user data with {{{ }}} in my views, But what should i do if i get the data with ajax ? It is a jquery variable i cant escape it with the brackets. For example if I handle response from ajax like :

$.each(response, function( key, value ) 
{
    $('#div').append('<div>'+value.notEscapedData+'<div>')
});

And the controller where the data comes from is for example.

$response = Data::all()
return $response;

You can either do it with javascript (and you will find plenty solutions on the internet. e.g. the link @Thrustmaster posted in the comments) or you can do it in Laravel.

When you use Blades triple curly braces {{{ }}} it compiles to a call to e() (which then calls htmlentities)

So you can use e('string-containing-html') to escape the string.

You could use a model attribute accessor for the escaping but I suppose you will need the string unescaped sometimes so here are a two other options:

toArray()

Override the toArray() method in your model

public function toArray(){
    $array = parent::toArray();
    $array['attribute_name'] = e($array['attribute_name']);
    return $array;
}

This way every time the model gets converted into an array (which is used for converting it into JSON=, the property will be escaped.

Loop over it in your controller

$data = Data::all();
$data->each(function($d){
    $d->attribute_name = e($d->attribute_name);
});
return Response::json($data);