Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Laravel repositories with Datatables

In my Laravel 5.1.* project I make use of repositories via this https://github.com/andersao/l5-repository library. For Datatables I use this https://github.com/yajra/laravel-datatables library. Now I can get the data from my repository via dependency injection in my controller.

namespace Admin\Http\Controllers;

use App\Repositories\Contracts\ModuleRepository;

class ModuleController extends Controller
{
    /**
     * @var ModuleRepository
     */
    protected $repository;

    /**
     * ModuleController constructor.
     *
     * @param ModuleRepository $repository
     */
    public function __construct(ModuleRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return view('admin::pages.module.index');
    }

    /**
     * Return list with module data.
     *
     * @return mixed
     */
    public function data()
    {
        $modules = $this->repository->all();
        return $modules;
    }
}

The data method gets called via an Ajax request from the index page.

    var oTable = $('#modules-table').DataTable({
        stateSave: true,
        processing: true,
        serverSide: true,
        rowReorder: true,
        ajax: {
            url: '{!! url('admin/module/data') !!}',
            type: 'POST',
            data: { _token: '{!! csrf_token() !!}' }
        },
        columns: [
            {data: 'sequence', name: 'sequence'},
            {data: 'display_name', name: 'display_name'},
            {data: 'active', name: 'active', orderable: false, searchable: false},
            {data: 'config', name: 'config', orderable: false, searchable: false}
        ],
        language: {
            url: '{{ asset('/admin/localization/nl/datatable.json') }}'
        }
    });

To make this work I have to return a Datatables instance from my controller like this:

    return Datatables::of($modules)
        ->addColumn('active', function($module)
        {
            if (Config::get('modules.' . $module->name . '.active') == 1)
                return '<a href="'. url('admin/module/' . $module->id . '/disable') .'" class="label success"><i class="fa fa-eye fa-fw"></i> Ingeschakeld</a>';
            else
                return '<a href="'. url('admin/module/' . $module->id . '/enable') .'" class="label disabled"><i class="fa fa-eye-slash fa-fw"></i> Uitgeschakeld</a>';
        })
        ->addColumn('config', function($module)
        {
            return '<a href="'. url('admin/module/' . $module->id . '/edit') .'" class="label info"><i class="fa fa-pencil fa-fw"></i> Configuratie</a>';
        })
        ->make(true);

What is the best place to transform my repository data to a datatables instance? Do I have to create a transformer for this?

like image 584
kipzes Avatar asked Dec 24 '15 10:12

kipzes


1 Answers

I don't think that there is a need of creating presenter , i suggest to make things more simple (its actually my practice).

i put my datatable implementation in my repository class :

use Prettus\Repository\Eloquent\BaseRepository;

class MyRepository extends BaseRepository
{
    // .... 

    public function getDatatable()
    {
        $images = $this->model->select('*');
        return Datatables::of($images)
            ->addColumn('action', function ($p) {
                return '<a class="btn btn-xs btn-danger" onclick="return confirm(\'Delete this image ?\');" href="'.action('Dashboard\\ImagesController@destroy', ['id'=>$p->id]).'"><i class="glyphicon glyphicon-remove"></i> Delete</a>';
            })
            ->addColumn('image', function ($p) {
                return '<a href="'.$p->getMedia()[0]->getUrl().'"><img src="'.$p->getMedia()[0]->getUrl().'" class="img-responsive"></a>';
            })
            ->editColumn('created_at', '{!! $created_at->diffForHumans() !!}')
            ->make(true);
    }
}

and then simply on your controller

namespace Admin\Http\Controllers;

use App\Repositories\Contracts\ModuleRepository;

class ModuleController extends Controller
{

    protected $repository;

    // .......

    /**
     * Render a datatable instance
    */
    public function datatable()
    {
         return $this->repository->getDatatable();
    }
}
like image 199
Abdou Tahiri Avatar answered Nov 10 '22 23:11

Abdou Tahiri