Laravel-datatables: ¿Cómo enviar parámetros a la clase UsersDataTable del servicio DataTable?

Creado en 15 mar. 2017  ·  11Comentarios  ·  Fuente: yajra/laravel-datatables

¿Cómo paso los parámetros (user_id, username, etc.) a la clase DataTable Service UsersDataTable para consultas DB?

UsersController:

class UsersController extends Controller
{
    public function index(UsersDataTable $dataTable)
    {
        return $dataTable->render('users');
    }
}

¿Necesito personalizar las funciones en UsersDataTable Class como public function query($param) {} o public function ajax($param) {} ?

documentation enhancement question

Comentario más útil

Si está usando v7, puede usar:

class UsersController extends Controller
{
    public function index(UsersDataTable $dataTable)
    {
        return $dataTable->with('key', 'value')->render('users');
    }
}

Y acceda a él como una propiedad en la clase dataTable.

public function query() {
  $key = $this->key;
  ...
}

Todos 11 comentarios

Si está usando v7, puede usar:

class UsersController extends Controller
{
    public function index(UsersDataTable $dataTable)
    {
        return $dataTable->with('key', 'value')->render('users');
    }
}

Y acceda a él como una propiedad en la clase dataTable.

public function query() {
  $key = $this->key;
  ...
}

Este es el compromiso donde agregué esta funcionalidad en caso de que lo necesite. Aún no se agregó a la documentación.

hola, gracias por la respuesta, actualmente estoy usando 6.x para Laravel 5.3.30,

¿Funcionará si copio y pego el código de confirmación en las tablas de datos 6.x?

Agregué el código de confirmación al paquete Datatables 6.x, está funcionando bien solo que en la clase de servicio DataTable query() :

    public function query()
    {

        $id = $this->id;

        $restaurant = restaurant::where('res_id', $id);

        return $this->applyScopes($restaurant);

    }

el return $this->applyScopes($restaurant); , $restaurant muestra una advertencia:

Expected \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder, got \App\Models\restaurant less... (Ctrl+F1) 
Invocation parameter types are not compatible with declared.

pero si agrego ->get() like, return $this->applyScopes($restaurant->get()); la advertencia desaparecerá, pero la vista de la tabla de datos obtendrá un error como:

DataTables warning: table id=dataTableBuilder - ajax error.

http://prntscr.com/el53kh

¿Puedes pegar tu clase de restaurante? Creo que hay algún problema con tu modelo.

De todos modos, no es recomendable editar la carpeta del proveedor, así que decidí agregar las variables fluidas también en v6.

Actualice a v6.27.0 para tener esta función. ¡Gracias!

hola, esta es mi clase de modelo de restaurante actual:

<?php

namespace App\Models;

use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class restaurant
 *
 * <strong i="6">@package</strong> App\Models
 * <strong i="7">@version</strong> February 27, 2017, 5:13 pm UTC
 * <strong i="8">@property</strong> int $res_id
 * <strong i="9">@property</strong> string $res_name
 * <strong i="10">@property</strong> string $res_image
 * <strong i="11">@property</strong> string $res_image_date
 * <strong i="12">@property</strong> string $res_address
 * <strong i="13">@property</strong> string $res_state
 * <strong i="14">@property</strong> string $res_location
 * <strong i="15">@property</strong> string $res_area
 * <strong i="16">@property</strong> string $res_telephone
 * <strong i="17">@property</strong> int $res_min_price
 * <strong i="18">@property</strong> int $res_max_price
 * <strong i="19">@property</strong> float $res_latitude
 * <strong i="20">@property</strong> float $res_longitude
 * <strong i="21">@property</strong> bool $res_chain
 * <strong i="22">@property</strong> bool $res_new
 * <strong i="23">@property</strong> bool $res_offer
 * <strong i="24">@property</strong> bool $res_type_state
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\res_working_hour[] $workingHours
 * <strong i="25">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResAddress($value)
 * <strong i="26">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResArea($value)
 * <strong i="27">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResChain($value)
 * <strong i="28">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResId($value)
 * <strong i="29">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResImage($value)
 * <strong i="30">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResImageDate($value)
 * <strong i="31">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResLatitude($value)
 * <strong i="32">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResLocation($value)
 * <strong i="33">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResLongitude($value)
 * <strong i="34">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResMaxPrice($value)
 * <strong i="35">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResMinPrice($value)
 * <strong i="36">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResName($value)
 * <strong i="37">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResNew($value)
 * <strong i="38">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResOffer($value)
 * <strong i="39">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResState($value)
 * <strong i="40">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResTelephone($value)
 * <strong i="41">@method</strong> static \Illuminate\Database\Query\Builder|\App\Models\restaurant whereResTypeState($value)
 * <strong i="42">@mixin</strong> \Eloquent
 */
class restaurant extends Model
{
    //use SoftDeletes;

    public $table = 'fc_restaurant';
    public $timestamps = false;

    //const CREATED_AT = 'created_at';
    //const UPDATED_AT = 'updated_at';


    protected $dates = ['deleted_at'];

    protected $primaryKey = 'res_id';
    //protected $hidden = 'res_id';

    public $fillable = [
        'res_name',
        'res_image',
//        'res_image_date',
        'res_address',
        'res_state',
        'res_location',
        'res_area',
        'res_telephone',
        'res_min_price',
        'res_max_price',
        'res_latitude',
        'res_longitude',
        'res_chain',
        'res_new',
        'res_offer',
        'res_type_state'
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * <strong i="43">@var</strong> array
     */
//    protected $casts = [
//        'res_id' => 'integer',
//        'res_name' => 'string',
//        'res_image' => 'string',
//        'res_address' => 'string',
//        'res_state' => 'string',
//        'res_location' => 'string',
//        'res_area' => 'string',
//        'res_telephone' => 'string',
//        'res_min_price' => 'integer',
//        'res_max_price' => 'integer',
//        'res_latitude' => 'float',
//        'res_longitude' => 'float'
//    ];

    /**
     * Validation rules
     *
     * <strong i="44">@var</strong> array
     */
    public static $rules = [

    ];


    public function workingHours()
    {
        return $this->hasMany('App\Models\res_working_hour', 'res_id');
    }


}

Hola yajra, es $ key = $ this-> atributos; no $ key = $ this-> key; ¿Correcto?
Usé esta $ clave = $ esto-> atributos;

@jcduenasr la clase usa un método getter mágico que obtiene los valores de las claves en los atributos.

Hola, tengo dos campos de fecha en un formulario para filtrar la consulta de la tabla por fechas y evitar que me traiga miles de registros.
El problema es que cuando intento exportar con uno de los botones, la consulta no envía los filtros de fecha, por lo que no traigo nada.
¿Cómo envío los campos de fecha usando los botones para exportar?

Esta es mi clase.
espacio de nombres AppDataTables;
usar App \ Accesos;
use YajraDatatables \ Services \ DataTable;

class AccesosDataTable extiende DataTable
{

public function ajax()
{   

    return $this->datatables
    ->eloquent($this->query())
    ->make(true);

}


public function html()
{
    return $this->builder()
                ->columns($this->getColumns())
                    ->ajax('')
                ->parameters([
                    'dom'          => 'Bfrtip',  
                    'buttons'      => ['export', 'reload'],
                ]);
}

public function query()
{
    $key = $this->attributes;
    $users = Accesos::whereBetween('field_filter',[$key['from'].' 00:00:00',$key['to'].' 23:59:59'])->select();

    return $this->applyScopes($users);

}

protected function getColumns()
{
    return [
        'field1',
        'field2',
        'field3',
        'field4',
        'field5',
        'field6',
    ];
}

    protected function filename()
    {
         return strtolower(trans('accesos'));
    }

}

¿Fue útil esta página
0 / 5 - 0 calificaciones

Temas relacionados

Mopster picture Mopster  ·  3Comentarios

techguydev picture techguydev  ·  3Comentarios

SGarridoDev picture SGarridoDev  ·  3Comentarios

jgatringer picture jgatringer  ·  3Comentarios

shadoWalker89 picture shadoWalker89  ·  3Comentarios