How To Display Relationship Data Into Yajra Datatables

Hello Artisan,

In this tutorial, I will show you yajra datatables with relationship data example. In this example, you will learn how to lead eager loading or relationship data in laravel in yajra datatable. 

So from this example, I will show you the example of how to display relationship data into yajra datatables. So if you don't know to display relationship or eager loading data in laravel then this tutorial is for you.

See the example of how to show relationship data in yajra datatable:

namespace App\Http\Controllers\System;

use App\Models\Manufacturer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\ManufacturerRequest;
use Yajra\DataTables\Facades\DataTables;

class ManufacturerController extends Controller
    public function index(Request $request)
        if ($request->ajax()) {
            $data = Manufacturer::with('address')->get();
            return DataTables::of($data)
                    ->addColumn('phone', function ($manufacturer) {
                        return $manufacturer->address->phone;
                    ->addColumn('action', function($row){
                        $editLink = route('manufacturer.edit',$row->ManufacturerID);
                        $deleteLink = route('manufacturer.delete',$row->ManufacturerID);
                        return button($editLink, $deleteLink);
        return view('system.manufacturer.index');


And just follow the below structure to display relationship data in yajra datatable:

$(function () {
        var table = $('.data-table').DataTable({
          ajax: "{{ route('manufacturer') }}",
          columns: [
              {data: 'ManufacturerID', name: 'ManufacturerID'},
              {data: 'ManufacturerName', name: 'ManufacturerName'},
              {data: 'phone', name: ''},
              {data: 'action', name: 'action', orderable: true, searchable: true},


Read also: How to Enable Order By Desc in Yajra Datatable Example


Hope it can help you.


#laravel #laravel-9x #yajra-datatables