Ad

How To Make Column Data Clickable With Link In Yajra Datatable Laravel 5.7

Im trying make the row values of the ID clickable that links to another view. This is achievable using the regular datatable from jQuery in the front-end like: <td><h6><a target="_blank" rel="nofollow noreferrer" href="/users/{{ $user->id }}">{{ $user->id }}</a></h6></td>. But how do I do it using yajra? For some reason, yajrabox.com won't load in my end so I couldn't read their docs. I can't find relevant tutorials either. Here's what I have so far.

UsersController:

public function index()
{        
    return view('users.index');
}

public function yajraDT()
{
    return Datatables::of(User::query())->make(true);
}

index.blade.php:

<div class="container">
<h2>Laravel DataTables Tutorial Example</h2>
    <table class="table table-bordered" id="tableDT">
        <thead>
            <tr>
                <th class="text-left">Id</th>
                <th class="text-left">First Name</th>
                <th class="text-left">Last Name</th>
                <th class="text-left">Email</th>
                <th class="text-left">Gender</th>
                @if(Auth::check() && Auth::user()->type == "Admin")
                <th class="text-left">Actions</th>
                @endif
            </tr>
        </thead>
    </table>

<script>
     $(function() {
           $('#tableDT').DataTable({
           processing: true,
           serverSide: true,
           ajax: '{{ url('users/yajraDT') }}',
           columns: [
                    { data: 'id', name: 'id' },
                    { data: 'first_name', name: 'first_name' },
                    { data: 'last_name', name: 'last_name' },
                    { data: 'email', name: 'email' },
                    { data: 'gender', name: 'gender' }
                 ]
        });
     });
</script>

routes.web:

Route::get('users/yajraDT', '[email protected]');
Route::resource('users', 'UsersController');
Ad

Answer

You can pass a render function to your data like so:

{ data: 'id', name: 'id', render:function(data, type, row){
    return "<a href='/users/"+ row.id +"'>" + row.id + "</a>"
}},

This will wrap all of the <td> in that anchor tag. I am wondering if you will run into problems with DataTable's own ID attribute, though. So I'm not sure if the row.id will return your id or DataTables. If you add a console.log(row) before the return statement you should find the object that you can manipulate in the render function, so you should be able to find what you need in there if row.id isn't returning the correct id.

Ad
source: stackoverflow.com
Ad