How to Display Image in DataTable with yajra laravel-datatables with laravel generator

In this tutorial, we are going to learn how to display image in datatable or add image column to datatable while using yajra/laravel-datatables with infyom laravel generator.

We are continuously getting some questions like how we can achieve something with laravel generator. Recently, we got a question like, how we can display Image in DataTable while using yajra/laravel-datatables with infyom laravel generator. so I thought maybe it can be requirements to lots of other developers as well and tried myself to find a solution. And then I decided to write a tutorial on that, so other developers can get an idea on that.

so here is the use case, suppose we have a Post model which contains three fields,

  1. Title
  2. Image
  3. Body

Image field contains a full or relative URL of the image which we need to show in datatable (same as above image). 

When you are using InfyOm Laravel Generator it generates PostDataTable.php file for the definition of DataTable. That file contains function named, getColumns() for the definition of columns of DataTable. Something like following,

return [
    'title' => ['name' => 'title', 'data' => 'title'],
    'image' => ['name' => 'image', 'data' => 'image'],
    'body' => ['name' => 'body', 'data' => 'body']

This is a very simple implementation of a DataTable Column definition.

To Display image in DataTable, we need to use `render` function on the column to display images. You can define your own render function which will return the data, that should be rendered in the column. In our case, we want to render an image, so our render function will be something like following,

return [
    'title' => ['name' => 'title', 'data' => 'title'],
    'image' => ['name' => 'image', 'data' => 'image'],
    'body' => ['name' => 'body', 'data' => 'body']

If you will look carefully, we are returning, <img src=""+data+"" height="50"/> from render function. Where data will be the data from the model. In our case, It will be a URL.
Render function gets the data parameter as a first argument. You can find more information about render function over here.

Above code will generate output something like following,

    "name": "image",
    "data": "image",
    "render": function (data, type, full, meta) {
        return "<img src=\"" + data + "\" height=\"50\"/>";
    "title": "Image",
    "orderable": true,
    "searchable": true

So, this is how we can display an image in datatable.