Donations Appreciated

It's not how much we give but how much love we put into giving. - Mother Teresa

Click here to lend your support to: Laravel Datatables and make a donation at pledgie.com !

EloquentController.php - Eloquent Datatable with Eager Loading

Heads Up! When searching/sorting for eager loaded models, your column name must be declared like relation.column

columns: [{data: 'id', name: 'posts.id'}, {data: 'user.name', name: 'user.name'}]

Important! To avoid ambiguous column name error, it is advised to declare your column name as table.column just like on how you declare it when using a join statements.

columns: [
    {data: 'id', name: 'posts.id'},
    {data: 'title', name: 'posts.title'},
    {data: 'user.name', name: 'user.name'},
    {data: 'user.email', name: 'user.email'},
    {data: 'created_at', name: 'posts.created_at'},
    {data: 'updated_at', name: 'posts.updated_at'}
]

If your relations consists of (2) two or more words, the convention to use is as follows:

{data: 'relation_name.column', name: 'relationName.column'}
Searching available since v6.4.0.
Sorting available since v6.7.0.
It is advised that you include select('table.*') on query to avoid weird issues where id from related model replaces the id of the main model.
$posts = Post::with('user')->select('posts.*');
Id Title Author Name Email Created At Updated At

EloquentController.php

    public function getRelationships()
    {
        return view('datatables.eloquent.relationships');
    }

    public function getRelationshipsData()
    {
        $posts = Post::with('user')->select('posts.*');

        return Datatables::of($posts)
            ->editColumn('title', '{!! str_limit($title, 60) !!}')
            ->make(true);
    }

Javascript

    $('#posts-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: 'https://datatables.yajrabox.com/eloquent/relationships-data',
        columns: [
            {data: 'id', name: 'posts.id'},
            {data: 'title', name: 'posts.title'},
            {data: 'user.name', name: 'user.name'},
            {data: 'user.email', name: 'user.email'},
            {data: 'created_at', name: 'posts.created_at'},
            {data: 'updated_at', name: 'posts.updated_at'}
        ]
    });