Home > Mobile >  How can I list user roles in new line in datatables and laravel 8
How can I list user roles in new line in datatables and laravel 8

Time:10-08

I'm working with laravel 8 and datatables, I'm listing data of registered users in my application, everything is working fine, but I have a column named roles where I want to list all the roles that are associated to a user, I can get the roles this way: enter image description here

But what I want is to show roles like this:

  • Role 1
  • Role 2
  • Role 3

This is the code in my controller

//Getting users with the name of associated roles 
    $users = User::with('roles')->get();
    $users = $users->transform(function($item){
        $item->role_names = $item->roles->pluck('name')->implode(' ');
        return $item;
    })->all();

I'm using implode method to separate the data, I've tried using this to display the info in a new line, but it doesn't work

->implode('<br>');

This is how I'm rendering the datatable in my js file:

        "columns" : [
            {data : 'id' , className : 'id'},
            {data : 'name', className : 'name'},
            {data : 'email', className : 'email'},
            {data : 'role_names', className : 'roles'},
            {data : 'status', className : 'status'},
            {data : 'actions', className : 'actions'},
        ]

Any idea? thanks.

CodePudding user response:

You should not be using your controller to modify the appearance of data, that is the job of the view. In this case, you can use the Datatables column.render function to format the data how you desire using a callback function, something like this:

$('#example').dataTable({
    "columns" : [
        {data : 'id' , className : 'id'},
        {data : 'name', className : 'name'},
        {data : 'email', className : 'email'},
        {data : 'roles', className : 'roles', render: function(data) {
            // data is your array of roles, do what you like with it
            let names = data.map(x => x.name);
            return names.join("<br/>");
            
        }},
        {data : 'status', className : 'status'},
        {data : 'actions', className : 'actions'},
    ]
});
  • Related