Laravel datatable shows role name

Viewed 1250

good I have users with different roles, and I would like to know how I can show in my datatable instead of the id of the role, I want to see the name of the role ..

public function index(Request $request)
{
   // $users = User::orderBy('id', 'ASC')->paginate(5);
    //return view('admin.users.index', ['users' => $users]);
    if($request->ajax()){

        $data = User::latest()->get();
        return DataTables::of($data)
            ->addColumn('accion',function($data){
                $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Edit</button>';
                $button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
                return $button;
            })
        ->rawColumns(['accion'])
        ->make(true);
    }
    return view('admin.users.index');
}

datatable.js

$(document).ready( function () {
   $('#table').DataTable({
            processing: true,
            serverSide: true,
            ajax: "/admin/users/",
            columns:
            [
              {
                data: 'id',
                name: 'id',
              },
              {
                 data:'name',
                 name: 'name',
              },
              {
                 data:'email',
                 name: 'email',
              },
              {
                 data:'role_id',
                 name: 'role_id',
              },
              {
                 data:'accion',
                 name: 'accion',
                 orderable:false
              },
            ]
        });
} );

it shows me the id of the role, but I want to access the name property of the role

2 Answers

First you want to make sure you're loading the role information when you query the user data, to prevent multiple queries

$data = User::with('role')->latest()->get();

Then you add role.name to your datatable:

{
    data: 'role.name',
    name: 'role'
}

These examples assume you have the relationship already set up on the user model and it's named "roles".

From controller or route, it's just an example

Route::get('/table_data', function (Request $request) {

$columns = array( 
    0 => 'id', 
    1 => 'key', 
    2 => 'doc_name',
    3 => 'name',
    4 => 'email',
    5 => 'phone',
    6 => 'city',
    7 => 'options'
);

//Below are some code for pagination of datatable and counts etc...
$totalData = Patient::count();
$totalFiltered = $totalData;

$limit = $request->input('length');
$start = $request->input('start');
$order = $columns[$request->input('order.0.column')];
$dir = $request->input('order.0.dir');
if(empty($request->input('search.value'))){
    $patients = Patient::offset($start)
                ->limit($limit)
                ->orderBy($order,$dir)
                ->get();
}
else
{
    //Below code is for search facility real time searching in datatable
    $search = $request->input('search.value'); 
    $patients =  Patient::with('doctor')
                ->where('name', 'LIKE', "%{$search}%")
                ->orWhere([
                    ['email', 'LIKE', "%{$search}%"],
                    ['phone', 'LIKE', "%{$search}%"],
                    ['city', 'LIKE', "%{$search}%"]
                ])
                ->offset($start)
                ->limit($limit)
                ->orderBy($order,$dir)->get();

    $totalFiltered = Patient::with('doctor')->where('name','LIKE',"%{$search}%")->orWhere([
                    ['email', 'LIKE', "%{$search}%"],
                    ['phone', 'LIKE', "%{$search}%"],
                    ['city', 'LIKE', "%{$search}%"]
                ])->count();
}

$data = array();

if(!empty($patients))
{
    foreach ($patients as $key=>$patient)
    {
        $nestedData['id'] = $patient->id;
        $nestedData['key'] = $key;
        //Here this is what I wanted to point out for you, it's a relationship, like in your case it will be something like $user->role->name
        $nestedData['doc_name'] = $patient->doctor->name;
        $nestedData['name'] = $patient->name;
        $nestedData['email'] = $patient->email;
        $nestedData['phone'] = $patient->phone;
        $nestedData['city'] = $patient->city;

        $nestedData['options'] = '<div class="btn-group">
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action
                      <span class="caret"></span>
                      <span class="sr-only">Toggle Dropdown</span>
                    </button>
                    <ul class="dropdown-menu edit-options dropdown-menu-right dropdown-default" user="menu">
                    <li>
                        <button="type" class="btn btn-link view"><i class="fa fa-eye"></i> View</button>
                    </li><li>
                    <a href="#" class="btn btn-link"><i class="fa fa-edit"></i> Edit</a>
                </li><li>
                      <button type="submit" class="btn btn-link" onclick="return confirmDelete()"><i class="fa fa-trash"></i> Delete</button> 
                    </li>
                </ul>
            </div>';

        $nestedData['patient'] = array( '[ "'.$nestedData['id'].'"', ' "'.$nestedData['key'].'"', ' "'.$nestedData['name'].'"', ' "'.$nestedData['email'].'"', ' "'.$nestedData['phone'].'"', ' "'.$nestedData['city'].'"]'
        );
        $data[] = $nestedData;
    }
}

$json_data = array(
    "draw"            => intval($request->input('draw')),  
    "recordsTotal"    => intval($totalData),  
    "recordsFiltered" => intval($totalFiltered), 
    "data"            => $data   
);

  echo json_encode($json_data);
});

And inside datatable you will do something like this

$('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        // "scrollY": 200,
        // "deferRender": true,
        // "scroller": true,
        "ajax":{
            url:"{{ url('table_data') }}",
            dataType: "json",
            type:"get"
        },
        "createdRow": function( row, data, dataIndex ) {
            $(row).addClass('patient-link');
            $(row).attr('data-patient', data['patient']);
        },
        "columns": [
            {"data": "key"},
            {"data": "doc_name"},
            {"data": "name"},
            {"data": "email"},
            {"data": "phone"},
            {"data": "city"},
            {"data": "options"}
        ],
        'language': {
            'searchPlaceholder': "Type patient name",
            'lengthMenu': '_MENU_ records per page',
            "info": 'Showing _START_ - _END_ (_TOTAL_)',
            "search": ' Search',
            'paginate': {
                    'previous': 'Previous',
                    'next': 'Next'
            }
        },
        'columnDefs': [
            {
                orderable: false,
                targets: [0, 6],
            },
            {
                'targets': 0
            }
        ],
        order:[[1, 'asc']],
        'lengthMenu': [[10, 25, 50, -1], [10, 25, 50, "All"]],
        dom: '<"row"lfB>rtip'
    } );

Note: I have pasted this full code because it took me a lot of time for the datatable to work in laravel, you can add checkboxes and buttons as well. And I think that this code will help many people who are really new to laravel with datatable, and most important this includes datatable full features by just enabling it's libraries, and everything will work

Related