Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How to use rawColumns() or escapeColumns() in Yajra Datatables?


How to use rawColumns() or escapeColumns() in Yajra Datatables?


To render HTML in columns using Yajra DataTables, you can use the `rawColumns()` method:

[2][4]
To render HTML in a specific column, you need to add the column name to the `rawColumns()` array:

php
return DataTables::eloquent(Role::select())
    ->rawColumns(['name', 'action'])
    ->toJson();

This will render the contents of the 'name' and 'action' columns as HTML, while escaping the contents of all other columns to prevent XSS attacks.

Alternatively, if you want to escape all columns by default and only render specific columns as HTML, you can use the `escapeColumns()` method:

[2][3]

php
return DataTables::eloquent(Role::select())
    ->escapeColumns()
    ->rawColumns(['name', 'action'])
    ->toJson();

This will escape the contents of all columns by default, and only render the 'name' and 'action' columns as HTML.

You can also use the `escapeColumns()` method to escape specific columns while rendering the rest as HTML:

[2]

php
return DataTables::eloquent(Role::select())
    ->escapeColumns(['email'])
    ->rawColumns(['name', 'action'])
    ->toJson();

This will escape the 'email' column while rendering the 'name' and 'action' columns as HTML.

The key points are:

1. Use `rawColumns()` to specify which columns should be rendered as HTML.
2. Use `escapeColumns()` to specify which columns should be escaped by default, and then use `rawColumns()` to override the default for specific columns.

Citations:
[1] https://stackoverflow.com/questions/52581186/laravel-datatables-json-column-escaping-chars
[2] https://yajrabox.com/docs/laravel-datatables/master/xss
[3] https://github.com/yajra/laravel-datatables/issues/909
[4] https://yajrabox.com/docs/laravel-datatables/master/raw-columns
[5] https://github.com/yajra/laravel-datatables/issues/1143