Laravel

How to display relationship data into Yajra DataTables with InfyOm Laravel Generator

display relationship data

Lots of people asked a question on our Github Repo about how they can display relationship data into index while using Datatables. so I decided to write a post with a detailed tutorial on that. Let’s see how it’s possible.

Problem:

Let’s imagine the following simple scenario. We have a users table and we have a posts table. Post table is pretty simple with the following fields:

  • id
  • author_id
  • title
  • body
  • created_at
  • updated_at

Where author_id is a foreign key to the users table. We want to display the author name into the index table.

But since we need that data from the relationship, there is no direct way to display that into Datatable.

Solution:

Let’s perform the following steps (before performing these steps, generate your CRUD with datatables for Post model):

Step 1: Add author relationship into Post model

Since we want to display the author name of the post, let’s add author relationship into Post.php

				
					public function author() {     
return $this->belongsTo(User::class, 'author_id'); 
}
				
			

Step 2: Modify PostDataTable

Since we have to display relationship data we need to load it using eager loading of laravel. Modify the query method of PostDataTable.php. something like,

				
					public function query(Post $model) {     
return $model->newQuery()->with(['author']); 
}
				
			

Also, we need to add one more column author name into the datatable. so modify getColumns method and add that to the array. something like,

				
					protected function getColumns() {     
return [        
       'title',         
       'author_name' => new \Yajra\DataTables\Html\Column([
       'title' => 'Author Name', 
       'data' => 'author.name',
       'name' => 'author.name'
      ])     
  ]; 
}
				
			

This will add one more column with header “Author Name” in the datatable before “Action” column. Here, we are adding custom datatable column where key will the name of column which datatable use internally, title will be used for Datatable Column header title and data will be used for retrieving data.

And that’s it. Run your code and you should be able to see Author name of the post into your datatable.

Share On: