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 a requirement for 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,
- Title
- Image
- Body
Image field contains a full or relative URL of the image which we need to show in a 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 a 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 images in DataTable, we need to use the `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,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;
},
"title": "Image",
"orderable": true,
"searchable": true
}