1

I want to implement DataTables as a service, so I have followed this tutorial: http://datatables.yajrabox.com/service

I have created a DataTable for my User collection using this command:

php artisan datatables:make UsersDataTable

So, in my app/DataTables/UsersDataTable.php I have configured it as shown:

I am trying to show records from two tables...

<?php

namespace App\DataTables;

use App\User;
use Yajra\Datatables\Services\DataTable;

class UsersDataTable extends DataTable
{
    public function ajax()
    {
        return $this->datatables
            ->eloquent($this->query())
            ->addColumn('action', '<button class="btn btn-primary">Edit</button>')
            ->make(true);
    }

    public function query()
    {
        $users = User::query()
            ->leftJoin('roles', 'roles.id', '=', 'users.role_id')
            ->select([
                'users.id',
                'users.name',
                'roles.name as role'
            ]);

        return $this->applyScopes($users);
    }

    public function html()
    {
        return $this->builder()
                    ->columns($this->getColumns())
                    ->ajax('')
                    ->addAction(['width' => '80px'])
                    ->parameters($this->getBuilderParameters());
    }

    private function getColumns()
    {
        return [
            'id',
            'name',
            'role'
        ];
    }

    protected function filename()
    {
        return 'users';
    }
}

This results in the following:

enter image description here

As you can see, this works as expected. This page runs on the following Url:

http://my-domain.local/users

How can I link the Edit button to a link like this:

http://my-domain.local/users/xxx/edit

Where xxx is the id of the row record?

2 Answers 2

3

I have solved it, this is how you do it:

public function ajax()
{
    return $this->datatables
        ->eloquent($this->query())
        ->addColumn('action', function($row) {
            return '<a href="/users/'. $row->id .'/edit" class="btn btn-primary">Edit</a>';
        })
        ->make(true);
}

Thanks to: https://github.com/yajra/laravel-datatables/issues/476

Sign up to request clarification or add additional context in comments.

Comments

0

If you need to add route path.., can do so as

 $actionBtn = '<a href="' . route("users", $row->id) . '" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-edit"></i> Edit</a>'; 

return $actionBtn;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.