Skip to content

Instantly share code, notes, and snippets.

@elton182
Created January 9, 2017 12:11
Show Gist options
  • Save elton182/444e8d2d07c340395732e6f4f841484b to your computer and use it in GitHub Desktop.
Save elton182/444e8d2d07c340395732e6f4f841484b to your computer and use it in GitHub Desktop.
<?php
namespace safed\Traits;
Trait DataTablesTrait{
/**
* receices the model collection with records and return a json needed for the datatable
* receives de name of the Controller to generate correct URLs
* receives the customfields (for relations) that you want to return with the json
*
* @param $records
* @param $name
* @param $customfields
*/
public static function getDataTableJson($records,$name = '',$Customfields = [])
{
$cont = 0;
$json = [];
foreach ($records as $record) {
$fields = [];
foreach ($record->getAttributes() as $key => $value) {
$fields[$key] = $record->{$key};
}
if (!empty($Customfields)) {
foreach ($Customfields['relations'] as $customfield => $customfieldvalue) {
foreach ($customfieldvalue as $fieldName) {
debug($fieldName);
$fields[$customfield . '_' . $fieldName] = $record->{$customfield}->{$fieldName};
}
}
}
$fields['actions'] = DataTablesTrait::withCrudActions($fields,$name);
array_push($json, $fields);
$cont++;
}
$data =
[
"draw" => 1,
"recordsTotal" => $cont,
"recordsFiltered" => $cont,
'data' => $json,
];
return json_encode($data);
}
public static function withCrudActions($array,$name){
$params = ['id' => $array['id']];
$consultar = '<a class="btn btn-info" href="'.action( $name . '@view', $params).'"> <i class="fa fa-eye" aria-hidden="true"></i></a>';
$editar = '<a class="btn btn-warning" href="'.action( $name . '@edit', $params).'"> <i class="fa fa-pencil" aria-hidden="true"></i></a>';
$excluir = '<a class="btn btn-danger" onclick=deleteRecord("'.$params['id'].'","'.action( $name . '@delete' ).'",refresh)><i class="fa fa-trash" aria-hidden="true"></i></a>';
// debug($consultar);
return $consultar . $editar . $excluir ;
}
}
?>
@elton182
Copy link
Author

elton182 commented Jan 9, 2017

To use it, make your Model use the trait, then on the controller create a method that calls the getDataTableJson
`

    $users= User::all();
    
    $params = ['relations' => ['customer' => ['name']]] ;

    echo User::getDataTableJson($users,'UserController',$params);

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment