yajra / laravel-datatables

jQuery DataTables API for Laravel
https://yajrabox.com/docs/laravel-datatables
MIT License
4.74k stars 861 forks source link

How to use transformers? #556

Closed willekaputra closed 8 years ago

willekaputra commented 8 years ago

Summary of problem or feature request

Hello I want to ask you how to apply transformers on controller. I already followed your documentation, then i got an exception that 'App\Transformers\DatatablesTransformer' does not exist. How do i create this class? Do i must create it manually?

yajra commented 8 years ago

Yes, you need to create it manually. See example transformer for ref. You also need to learn fractal.

namespace App\Transformers;

use League\Fractal\TransformerAbstract;
use Carbon\Carbon;

class DatatablesTransformer extends TransformerAbstract
{
    /**
     * @return array
     */
    public function transform(array $data)
    {
        return [
            'id'         => (int) $data['id'],
            'name'       => $data['name'] . ' - fractal',
            'email'      => $data['email'],
            'created_at' => $this->dateFormatter($data['created_at']),
            'updated_at' => $this->dateFormatter($data['updated_at']),
        ];
    }

    /**
     * @param null|DateTime $dateTime
     * @return string
     */
    public function dateFormatter($dateTime)
    {
        return $dateTime ? with(new Carbon($dateTime))->format($this->getDateFormat()) : null;
    }

    /**
     * @return string
     */
    public function getDateFormat()
    {
        return 'Y-m-d';
    }
}
willekaputra commented 8 years ago

Thank you for your answer.