Giter Site home page Giter Site logo

freshbitsweb / laratables Goto Github PK

View Code? Open in Web Editor NEW
486.0 18.0 65.0 153 KB

Ajax support of DataTables (Laravel 5.5 to Laravel 8.x)

License: MIT License

PHP 100.00%
php php7 laravel laravel5-package datatables datatables-serverside datatables-ajax datatables-configuration

laratables's People

Contributors

cjau avatar gauravmak avatar helissonms avatar hirenkeraliya avatar latheesan-k avatar liamdemafelix avatar sandermuller avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laratables's Issues

Limit is not a number

When I tried to use the package, it appears the message:

Expected "limit" option to have type "integer" but found "string"

I think that it can be easily corerected if you change, in the Laratables class, the lines:

->offset(request('start'))->limit(request('length'))

to:

->offset(intval(request('start')))->limit(intval(request('length')))

The offset didn't appear in the message, but I think that it could be done to prevent the error.

ErrorException Undefined index:

Server side
use App\User;
use Freshbitsweb\Laratables\Laratables;

function getdata()
{
return Laratables::recordsOf(User::class);
}

When run \getdata
Show
(1/1) ErrorExceptionUndefined index:

in ColumnManager.php line 168
at HandleExceptions->handleError(8, 'Undefined index: ', '/home/html/xxxx/vendor/freshbitsweb/laratables/src/ColumnManager.php', 168,array('requestedColumnNames' => array(), 'order' => null))in ColumnManager.php line 168
at ColumnManager->getOrderColumn()in ColumnManager.php line 145

MongoDB Support

i am trying to use laratables with mongodb and jessenger but am getting this error

Undefined index:
at $orderColumn = $requestedColumnNames[$order[0]['column']];
in public function getOrderColumn()

Simple Relationship help

Help, I can't get your instructions..

This is my school model:

class School extends Model
{
    public function schedules(){
        return $this->hasMany(Schedule::class);
    }
}

Controller:

    return LaraTables::recordsOf(School::class);

View:

    $('#table').DataTable({
    processing: true,
    serverSide: true,
    ajax: '/data',
    columns: [
        {name: 'school'},
        {name: 'address'},
        {name: 'contact'},
        {name: 'schedules.date', orderable: false}
    ],

It's not working. Is this how it is?

Handle custom request data

Hello,

I am working on a project using DataTables which means I need to use custom filters, along with server side pagination. These filters are

1. Show Inactive members" / "Show active members:
Currently a checkbox which sets a value on the request show_inactive = true|false

2. last Used Since / Upto

last_used = "20/02/2019 10:38"
last_used_operator = >= || <=

At the moment I am using the laratablesQueryConditions() method, with logic in side to look at the request() values, and perform the appropriate conditions on the query but just wondered if there was a better way?

Great package by the way!

Thanks

Get another column data using row[columnName] instead of row[columnIndex], is it possible?

Good day everyone,

In client-side I used 'data' to supply the column value, in Laratables as far as I know we need to use 'name' to select column from database, and returned as index [0, 1, n]

I can access other column via render using row[columnIndex], but how can I achieve it by row[columnName]?

Sample code:

{ title: 'Status', name: 'status', className: 'text-center', visible: false },
{ 
  title: 'Action', name: 'id', render: function(data, type, row) {
    // I want to access 'status' column from here
    if (row['status'] == 'T') return '1';
    else return '2';
  }
}

Thank you for your attention and support.
Thank you for making this great library! <3

Custom column with relation

Hello, I have some issue here, when I want to add new Column with format with a relationship field, I got an error, that the relationship is null.

public function User 
{
     return $this->belongsTo('App\User');
}

public function laratablesFullName()
{
        return $this->user->first_name.' '.$this->user->last_name;
}

the error said

Trying to get property 'first_name' of non-object

do I do something wrong?, sorry for bad English

got an error: ErrorException (E_NOTICE) Undefined index:

whenever i try to use getlaraData function i got this error-"udefined index"
my controller file:

User Name Email Password First Name Last Name Country @endsection @section('scripts') <script> $(document).ready(function() { $('#simple-datatable-example').DataTable({ serverSide: true, processing: true, responsive: true, ajax: "{{ route('admin.getlaraData') }}", columns: [ { name: 'username' }, { name: 'email' }, { name: 'password' }, { name: 'first_name' }, { name: 'last_name' }, { name: 'country' } ], }); }); </script> @endsection

[bug] Customizing column values with dedicated class

Hey

I utilize a dedicated class for the model datatables:

Laratables::recordsOf(Show::class, ShowDatatables::class);

at my ShowDatatables class i have

public function laratablesArchivedAt()

but laratables doesn't seem to recognize it. i'm getting the following error:

Call to undefined method App\Models\Show::laratablesArchivedAt()

The problem is at \Freshbitsweb\Laratables\RecordsTransformer::getColumnValue

if ($methodName = $this->customisesColumnValue($columnName)) { return $record->$methodName(); }

should be:

if ($methodName = $this->customisesColumnValue($columnName)) { return $this->class::$methodName($record); }

Unable to get relation

Hi

Whenever I try to retrieve relational data, it fails and gives the following errors:

error: "The 'image.source' column is not in the select column list. Please add it to the select columns or make it - orderable : false"

The relationship is a hasOne and checked that the relationship worked fine. The relationship is:

class Sponsor extends Model
{
    protected $table = 'sponsors';
    protected $with = ['image'];
....

public function image(){
        return $this->hasOne(Image::class, 'id', 'image_id');
    }

In the dataTable trying to pull the data as:

    columns: [
.....
                 {
                    name: 'image.source', render: function (data, type, row) {
                    return '<img src="' + data + '" class="circle circle-xs">';
                    },
                    orderable: false
                },

Table index Autoincrement numbers

How Can I archive table index with autoincrement number.I don't want to use with Eitity "id" field from database.If I delete something in id cannot be serialize.

Thanks!

customization

In my project customization doesn't work. For instance laratablesOrderName() or laratablesCustomAction()
ProjectController
`<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Project;
use Illuminate\Support\Facades\Validator;
use Freshbitsweb\Laratables\Laratables;

class ProjectController extends Controller
{

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index() {

return view('projects.index');
  
  }


    
 public function getCustomColumnDatatablesData()
{
   return Laratables::recordsOf(Project::class);        
}


/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
     return view('projects.create');
}

public function duplica($id)
{
    $project = project::find($id);
    $newproject = $project->replicate();

    $newproject->save();
    return redirect('/progetti')->with('success', 'Il progetto è stato duplicato');
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
  public function store(Request $request)
{
    // $request->validate([ 'Titolo'=>'required'      ]);
    $validator = Validator::make($request->all(), [
       'Titolo' => 'required'
   ]);
    
   if ($validator->fails()) {
        return redirect()->back()->withInput();
   }
       $Altri_Ambiti = $request->get('Altri_Ambiti');
       $Altri_Ambiti = implode (',', $Altri_Ambiti);

        
    $project = new project([
        'Titolo' => $request->get('Titolo'),
        'Settore_Principale' => $request->get('Settore_Principale'),
        'Area' => $request->get('Area'), 
        'Durata_Progetto' => $request->get('Durata_Progetto'),
        'Posti_Vitto_Alloggio' => $request->get('Posti_Vitto_Alloggio'),
        'Posti_Senza_Vitto_Alloggio' => $request->get('Posti_Senza_Vitto_Alloggio'),
        'Posti_Solo_Vitto' => $request->get('Posti_Solo_Vitto'),
        'Totale' => $request->get('Totale'),
        'Modalita' => $request->get('Modalita'),
        'Numero_Ore_Annue' => $request->get('Numero_Ore_Annue'),
        'Numero_Ore_Settimanali' => $request->get('Numero_Ore_Settimanali'),
        'Numero_Giorni_Settimanali' => $request->get(                           'Numero_Giorni_Settimanali'),            
        'Tipo_Finanziamento' => $request->get('Tipo_Finanziamento'),
        'Sistema_Selezione_Accreditato' => $request->get('Sistema_Selezione_Accreditato'),
        'Sistema_Monitoraggio_Accreditato' => $request->get('Sistema_Monitoraggio_Accreditato'),
        'Criteri_Selezione' => $request->get('Criteri_Selezione'),
        'Codice_Ente_Selezione' => $request->get('Codice_Ente_Selezione'),
        'Piano_Monitoraggio' => $request->get('Piano_Monitoraggio'),
        'Codice_Ente_Monitoraggio' => $request->get('Codice_Ente_Monitoraggio'),
        'Ore_Promozione' => $request->get('Ore_Promozione'),
        'Criteri_Formativi' => $request->get('Criteri_Formativi'),
        'Tirocini' => $request->get('Tirocini'),
        'Competenze' => $request->get('Competenze'),
        'Durata_Formazione_Generale' => $request->get('Durata_Formazione_Generale'),
        'Modalita_Attuazione_Formazione_Generale' => $request->get('Modalita_Attuazione_Formazione_Generale'),
        'Codice_Ente_Formazione_Formazione_Generale' => $request->get('Codice_Ente_Formazione_Formazione_Generale'),
        'Modalita_Erogazione_Formazione_Generale' => $request->get('Modalita_Erogazione_Formazione_Generale'),
        'Entro_90_Giorni_Formazione_Generale' => $request->get('Entro_90_Giorni_Formazione_Generale'),
        'Ultimi_3_Mesi_Formazione_Generale' => $request->get('Ultimi_3_Mesi_Formazione_Generale'),
        'Durata_Formazione_Specifica' => $request->get('Durata_Formazione_Specifica'),
        'Modalita_Attuazione_Formazione_Specifica' => $request->get('Modalita_Attuazione_Formazione_Specifica'),
        'Codice_Ente_Formazione_Formazione_Specifica' => $request->get('Codice_Ente_Formazione_Formazione_Specifica'),
        'Modalita_Erogazione_Formazione_Specifica' => $request->get('Modalita_Erogazione_Formazione_Specifica'),
        'Entro_90_Giorni_Formazione_Specifica' => $request->get('Entro_90_Giorni_Formazione_Specifica'),
        'Ultimi_3_Mesi_Formazione_Specifica' => $request->get('Ultimi_3_Mesi_Formazione_Specifica'),
        'Progetto_in_Cooperazione' => $request->get('Progetto_in_Cooperazione')

    ]);
    $project['Altri_Ambiti'] = $Altri_Ambiti;

    $project->save();
    return redirect('/progetti')->with('success', 'Progetto salvato correttamente');
}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */

public function show($id)
{
//
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{ 
    $project = project::find($id);
    return view('projects.edit', compact('project'));  
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    
    $project = project::find($id);
    $project->Titolo =  $request->get('Titolo');

// $request->validate([ 'Titolo'=>'required' ]);
$validator = Validator::make($request->all(), [
'Titolo' => 'required'
]);

   if ($validator->fails()) {
        return redirect()->back()->withInput();
   }
       $Altri_Ambiti = $request->get('Altri_Ambiti');
       $Altri_Ambiti = implode (',', $Altri_Ambiti);
        $project->Settore_Principale = $request->get('Settore_Principale');
        $project->Area = $request->get('Area'); 
        $project->Durata_Progetto = $request->get('Durata_Progetto');
        $project->Posti_Vitto_Alloggio = $request->get('Posti_Vitto_Alloggio');
        $project->Posti_Senza_Vitto_Alloggio = $request->get('Posti_Senza_Vitto_Alloggio');
        $project->Posti_Solo_Vitto = $request->get('Posti_Solo_Vitto');
        $project->Totale = $request->get('Totale');
        $project->Modalita = $request->get('Modalita');
        $project->Numero_Ore_Annue = $request->get('Numero_Ore_Annue');
        $project->Numero_Ore_Settimanali = $request->get('Numero_Ore_Settimanali');
        $project->Numero_Giorni_Settimanali = $request->get('Numero_Giorni_Settimanali');            
        $project->Tipo_Finanziamento = $request->get('Tipo_Finanziamento');
        $project->Sistema_Selezione_Accreditato = $request->get('Sistema_Selezione_Accreditato');
        $project->Sistema_Monitoraggio_Accreditato = $request->get('Sistema_Monitoraggio_Accreditato');
        $project->Criteri_Selezione = $request->get('Criteri_Selezione');
        $project->Codice_Ente_Selezione = $request->get('Codice_Ente_Selezione');
        $project->Piano_Monitoraggio = $request->get('Piano_Monitoraggio');
        $project->Codice_Ente_Monitoraggio = $request->get('Codice_Ente_Monitoraggio');
        $project->Ore_Promozione = $request->get('Ore_Promozione');
        $project->Criteri_Formativi = $request->get('Criteri_Formativi');
        $project->Tirocini = $request->get('Tirocini');
        $project->Competenze = $request->get('Competenze');
        $project->Durata_Formazione_Generale = $request->get('Durata_Formazione_Generale');
        $project->Modalita_Attuazione_Formazione_Generale = $request->get('Modalita_Attuazione_Formazione_Generale');
        $project->Codice_Ente_Formazione_Formazione_Generale = $request->get('Codice_Ente_Formazione_Formazione_Generale');
        $project->Modalita_Erogazione_Formazione_Generale = $request->get('Modalita_Erogazione_Formazione_Generale');
        $project->Entro_90_Giorni_Formazione_Generale = $request->get('Entro_90_Giorni_Formazione_Generale');
        $project->Ultimi_3_Mesi_Formazione_Generale = $request->get('Ultimi_3_Mesi_Formazione_Generale');
        $project->Durata_Formazione_Specifica = $request->get('Durata_Formazione_Specifica');
        $project->Modalita_Attuazione_Formazione_Specifica = $request->get('Modalita_Attuazione_Formazione_Specifica');
        $project->Codice_Ente_Formazione_Formazione_Specifica = $request->get('Codice_Ente_Formazione_Formazione_Specifica');
        $project->Modalita_Erogazione_Formazione_Specifica = $request->get('Modalita_Erogazione_Formazione_Specifica');
        $project->Entro_90_Giorni_Formazione_Specifica = $request->get('Entro_90_Giorni_Formazione_Specifica');
        $project->Ultimi_3_Mesi_Formazione_Specifica = $request->get('Ultimi_3_Mesi_Formazione_Specifica');
        $project->Progetto_in_Cooperazione = $request->get('Progetto_in_Cooperazione');
    $project['Altri_Ambiti'] = $Altri_Ambiti;

    $project->save();

    return redirect('/progetti')->with('success', 'Il progetto è stato aggiornato');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $project = project::find($id);
    $project->delete();

    return redirect('/progetti')->with('success', 'Il progetto è stato cancellato');
}

}
Model Project ....
public static function laratablesOrderName()
{
return 'Titolo';
}View

    <thead>

        <tr>

            <th>Num.</th>

            <th>Titolo</th>

            <th>Tot.Vol.</th>

            <th width="280px">Azioni</th>

        </tr>

    </thead>

    <tbody>

    </tbody>

</table>
<div class="modal-dialog">

    <div class="modal-content">

        <div class="modal-header">

            <h4 class="modal-title" id="modelHeading"></h4>

        </div>

        <div class="modal-body">

            <form id="projectForm" name="projectForm" class="form-horizontal">

               <input type="hidden" name="id" id="id">

                <div class="form-group">

                    <label for="name" class="col-sm-2 control-label">Titolo</label>

                    <div class="col-sm-12">

                        <input type="text" class="form-control" id="Titolo" name="Titolo" placeholder="Titolo" value="" maxlength="50" required="">

                    </div>

                </div>

 

                <div class="form-group">

                    <label class="col-sm-2 control-label">Totale volontari</label>

                    <div class="col-sm-12">

                        <textarea id="Totale" name="Totale" required="" placeholder="Totale vol." class="form-control"></textarea>

                    </div>

                </div>

  

                <div class="col-sm-offset-2 col-sm-10">

                 <button type="submit" class="btn btn-success" id="saveBtn" value="create">Salva
                 </button>

                </div>

            </form>

        </div>

    </div>

</div>
@Push('scripts') <script type="text/javascript"> $(document).ready(function() { $('#projects-table').DataTable({ serverSide: true, processing: true, responsive: true, language: { "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Italian.json"}, ajax: "{{ route('custom_column_datatables_projects_data') }}", columns: [ { name: 'id', orderable: false, searchable: false }, { name: 'Titolo', orderable: true, searchable: true }, { name: 'Totale', orderable: true, searchable: false } ] }); }); </script>

@endpush
`

Relationship column name not found in select list

columns: [
{ name: 'committee.name', orderable: false },
{ name: 'school'},
{ name: 'firstname'},
{ name: 'control', orderable: false, searchable: false},
{ name: 'message_flag', visible: false},
{ name: 'committee_id', visible: false},
]

Relationship Sorting

I am having trouble sorting the table by a relationship column.
Imagine a products table with the columns: id, name, store.name.
If I set store.name to be sortable, I get an error.

How can I make the Store Name sortable? I have this function but with no avail:

public static function laratablesOrderStoreName()
{
    return 'store.Name';
}

What am I doing wrong?

Thanks

'Array to String Conversion' 500 Error

Hi all,

I am desperately trying to get this to work, using the most basic vanilla code. My AJAX controller is returning the following error:

Array to string conversion /var/www/test-october/vendor/october/rain/src/Html/BlockBuilder.php line 80

Here is my table:

Date/time User Event

Here is my JS:

$('#settlementLogs').DataTable({ serverSide: true, processing: true, responsive: true, ajax: ajaxUrl, columns: [ {name: 'created_at'}, {name: 'user_id'}, {name: 'event'} ] });

Here is my controller action:

public function ajax() { return Laratables::recordsOf(TempoAudit::class); }

This is driving me crazy. The stack trace is just a load of low level system stuff that isn't any use. My setup is Laravel 5.5 within an October CMS app. No problems using DataTables so far.

Help greatly appreciated - thanks!

How to have a blank column ?

I have a column that contains a checkbox defined like this

'columns':[ { 'orderable': false, 'data': 'isChecked', 'defaultContent' : '', 'class': 'map-check', 'searchable': false, "title": "<input type='checkbox' />", "render": function () { return "<input type='checkbox'/>"; } },

laratables is producing a query with a blank field name for this column

Column not found: 1054 Unknown column '' in 'field list' (SQL: select id, ``, name, description,

How should I define this column so that it gets ignored in the sql query.

Thanks for any replies.

laratablesRowClass in custom table class

Hi, I've created a custom class to store the Laratables logic, so my model is cleaner.

When I try to add the laratablesRowClass function to my custom class to add custom CSS class names to table rows, I receive an error that CompletedAudit->laratablesRowClass is undefined.

If I then also add a laratablesRowClass function to the model, and put my logic in there, the class names are added.

If I then remove the laratablesRowClass from my custom Laratables class, but leave it in the model, it stops working as if it isn't even there.

Is this intended behaviour, or should I be able to put a function called laratablesRowClass in my custom Laratables class and it is all picked up from there?

Controller method:

   public function completed_audits_datatables() {
      return Laratables::recordsOf(CompletedAudit::class,CompletedAuditsTable::class);
    }

Laratables class:

<?php
  namespace App\Laratables;

  use App\CompletedAudit;

  class CompletedAuditsTable 
  {
    ...

    /**
     * Bug in laratables? - needed as stub here and function in model to be picked up.
     */
    public function laratablesRowClass() { }
  }

Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;

class CompletedAudit extends Model implements Auditable
{
    ...

    public function laratablesRowClass() {
      $class = $this->type->colour ? $this->type->colour.' lighten-4' : null;
      return $class;
    }
}

Getting the actual value of what i selected

I have a table, on of the columns is username, it is the first column.
i use this code to retrieve the values, because i saw this being used in the online example.

$('#users-table').on('click', 'tr',function(){
  alert(Object.values($(this)));
});

The problem is that the alert shows this: [object HTMLTableRowElement],[object HTMLTableRowElement],1
How could i get a specific value from the table? I want to use it further in a variable, redirect to a different site, and so on.

Non-static methods for changing column data in custom classes always call base class instead of custom class

From controller:

public function retrieveOrderTransactions()
{
    return Laratables::recordsOf(Transaction::class, OrderTransactions::class);
}

From class OrderTransactions (custom class holding laratables custom funtions):

public static function laratablesAdditionalColumns()
{
    return ['id'];
}

public static function laratablesCustomId($transaction)
{
    return 'ID: ' . $transaction->id;
}

This will correctly yield "ID: id" for each row.

If you change the laratablesCustomId() function to this:

public function laratablesId()
{
    return 'ID: ' . $this->id;
}

You get this error:

Call to undefined method App\Models\Transaction::laratablesId()

This is because in laratables/src/RecordsTransformer.php on line 81:

    if ($methodName = $this->customisesColumnValue($columnName)) {
       return $record->$methodName();
    }

$record is always an instance of App\Models\Transaction (base class) and not an instance of OrderTransactions (my custom class) even though in
$this->customisesColumnValue($columnName) the package checks to see if the desired method exists on the custom class ($this->class).

 protected function customisesColumnValue($columnName)
 {
    $methodName = camel_case('laratables_'.$columnName);

    if (method_exists($this->class, $methodName)) {`
        return $methodName;`
    }

    return false;
 }

I'm not sure if this is a bug or only custom methods are supposed to be used on custom classes. Is this how the package is intended to work?

Any help would be greatly appreciated. Thanks.

Nested Arrays

Hi

I am having some issues with arrays, I have a relational query that fetches the results and returns as an array.

I have tied many methods to access the data that is within the array but can not get it to work.
This is how the results are returned.
4: {name: "Bob Smith"}
name: "Bob Smith"

This is the Datatable line
{ name: 'assignedLink.name', orderable: false },

Any advice would be helpful.

Kind regards

Phil

Integration with Datatables Editor

Is it possible to use Laratables with Datatables.net Editor? So far, I have not been able to find any information about how to accomplish this.

Buttons in sub blade

Hi

I like the project but maybe I am missing something.

I have a table blade with an action blade for buttons.

I have tried various ways but i can not get variables to the buttons, maybe i am missing something?
I have even added an on click script to the table row which shows a variable correctly.
But then i move it to the button it runs but the variable comes back as undefined.

Hopefully someone will have some pointers

Kind regards

Phil

Pivot Table with no PK - Deselecting 'id' from Query

I have many to many relationship where its pivot has extra attribute than foreign key of both many tables.

When I try to fetch the data using Laratables, its resulting

Column not found: 1054 Unknown column 'id' in 'field list'

The reason I don't want to select is because my pivot table has no ID, it doesnt matter right?

My question is how I can ignore that 'id' from the pivot table so I can just select each foreign key and the extra attribute from my pivot table?

When I try to add property to my pivot model

protected $primaryKey = null;

It results:

Column not found: 1054 Unknown column '' in 'field list' (SQL: select ``, name,

Can I do this without ID? Or having ID on a pivot table become a must?


I tried to load the pivot using many table using withPivot(), but I'm having issue here that is very strange and can't resolve it currently, if any of you have experience using withPivot() I'll be grateful if you would share it here to me.

The error found when I access other many table is :
Property [id] does not exist on this collection instance.

Thank you.

HTML in column

First of all thank you for this nice package. I was able to significantly increase page load speed with this package!
One question:
I often use a table's last column to display some buttons like show, edit, delete.
How can i achieve this using your package?
In HTML i only specify the table header, the table body is completely handled by the client-side js code (the columns array), right? So how to put some HTML in the table body?
Cheers

SECURITY: Whitelist/Blackilist columns

Hi
Thank you for the package.
Cause of security issues we need to be able to define "whitelist" and "blacklist" columns, so these columns won't be searchable or orderable.

Add dpownload functionality

I am working on implementing laratables for downloading images. One of the database fields contains the file name.

Without laratables installed I can download like this
In my controller:
public function download($id) { $coa = Coa::find($id); return Storage::download('coapath/' . $coa->coa_name); }

How can I do this with laratables? I already added an extra column with a download button. But I am not able to trigger the download.

You can test it in coa.ozinc.work

I also created a seperate jQuery ajax function but it returns error
 coas.ozinc.work/publ…/uploads/OZ14.pdf:1 Failed to load resource: net::ERR_NAME_NOT_RESOLVED (index):137 GET http://coas.ozinc.work/public/uploads/BOC_FG_LEMFUEL_180820.sql net::ERR_NAME_NOT_RESOLVED
Here is my script:
` <script>
$(document).ready(function () {
$('#coa_table').DataTable({
serverSide: true,
processing: true,
responsive: true,
ajax: "{{ route('get_extra_data_datatables_attributes_data') }}",
columns: [
{name: 'id'},
{name: 'product_name'},
{name: 'coa_number'},
{name: 'coa_name'},
{name: 'action', orderable: false, searchable: false}

                ],
            });

            /*

                            $('#extra-data-datatables-attributes').on('click', 'tr', function () {
                                alert('Clicked row id is: ' + $(this).data('coa_name'));
                            }
            */

            $.ajaxTransport("+binary", function (options, originalOptions, jqXHR) {
                // check for conditions and support for blob / arraybuffer response type
                if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
                    return {
                        // create new XMLHttpRequest
                        send: function (_, callback) {
                            // setup all variables
                            var xhr = new XMLHttpRequest(),
                                url = options.url,
                                type = options.type,
                                // blob or arraybuffer. Default is blob
                                dataType = options.responseType || "blob",
                                data = options.data || null;

                            xhr.addEventListener('load', function () {
                                var data = {};
                                data[options.dataType] = xhr.response;
                                // make callback and send data
                                callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                            });

                            xhr.open(type, url, true);
                            xhr.responseType = dataType;
                            xhr.send(data);
                        },
                        abort: function () {
                            jqXHR.abort();
                        }
                    };
                }
            });
            $('#coa_table').on('click', 'tr', function () {

                var url = $(this).data('coa_path');
                $.ajax({
                    url: url,
                    type: "GET",
                    dataType: 'binary',
                    success: function (result) {
                        var url = URL.createObjectURL(result);
                        var $a = $('<a />', {
                            'href': url,
                            'download': 'document.txt',
                            'text': "click"
                        }).hide().appendTo("body")[0].click();
                        setTimeout(function () {
                            URL.revokeObjectURL(url);
                        }, 10000);
                    }
                });
            })

`

ErrorException (E_NOTICE) Undefined index

i get undefined index error when i try to use getlaraData function
my controller file

$(document).ready(function() { $('#simple-datatable-example').DataTable({ serverSide: true, processing: true, responsive: true, ajax: "{{ route('admin.getlaraData') }}", columns: [ { name: 'username' }, { name: 'email' }, { name: 'password' }, { name: 'first_name' }, { name: 'last_name' }, { name: 'country' } ], }); }); </script> @endsection

Feature request: sorting by custom calculated value

Hello,

I would like to be able to use datatables sorting with a column that doesn't exist in my database table. The column is actually a relationship column from another table on a one to many relationship. On the "many" side of the relationship I calculate the sum of the column and that is my value, id like to order on.

To give context:

  • I am showing a list of members
  • A member has many balance transactions (imagine like a bank statement)
  • The members current balance is the sum of the balance column on the above relationships "many"
  • I'd like to order by this calculated/ related column

Cheers

SSP enabled: show all rows

Hi,

How do we make use of pageLength parameter in SSP Laratables to return all DB rows? I have it working fine in plain DT... but, when implemented in Laratables, the 'All' pageLength returns an SQL syntax error. It's something like this:

"select id, product_base_id, sku, name, description, quantity, eol_status from rs_product_variants where rs_product_variants.deleted_at is null order by sku desc offset 1"

That's the query thrown by Laratables, and by removing the offset 1 value (manual query), fixes the problem. What am I missing? I'm trying to expose all records to make use of DT export buttons.

Thanks!

Individual column searching

Edit in the table. Can you update it here?
This should be a very common function.
However, there may be more types of forms to consider
If the author is willing to update

in addition
If I use more search status, how should datatable plug-ins be associated ?

case-insensitive search?

Great job!

I noticed, however, that by default the search is case-sensitive. Is there any config option, etc which will use a case-insensitive search?

extra filters

I want to pass some condition to the back-end and based on that condition I want to modify the query condition
for example

    public static function laratablesQueryConditions($query)
    {
        if($withTrashed == true){
           return $query->withTrashed();
        }
    }

How can I achieve this? as I need to find a way to pass another variable(maybe through $request or any other mean) but laratablesQueryConditions just takes one param
Please help

Undefined index:

Following the simple example and getting Undefined index:issue

<script>
        $('#users-table').DataTable({
            serverSide: true,
            ajax: "{{ route('riders.index') }}",
            columns: [
                { name: 'id' },
                { name: 'name' },
                { name: 'email' },
            ]
        });
        // $(document).ready( function () {
        //     $('#myTable').DataTable();
        // } );
    </script>
public function index(Request $request)
    {
        return Laratables::recordsOf(User::class);

Use something other than `orWhereHas` in search

First time I used laratables - really nice work!

I have a question. For a relationship column (one to many), I built custom searches CustomColumn (for formatting), thus I needed to use a CustomSearch for this column also. Think it like "Channel has many subscribers".

CustomValue shows all subscribers. The initial load is 500ms (very good). However, when I search,

public static function laratablesSearchSubsribers($query, $searchValue)
{
    return $query->orWhereHas('subscribers', function($q) use ($searchValue) {
        $q->where('cinema', 'like', '%'. $searchValue. '%');
    });
}

the whereHas causes 5.20s response time. In fact, I realised whereHas causes it to be very slow which I confirmed with my initial load.

public function getData() {
     // 3.36s
     return Laratables::recordsOf(Movie::class, function($q) {
         return $q->whereHas('subscribers');
     });

    // 400ms
    return Laratables::recordsOf(Movie::class, function($q) {
        return $q->where('subscribable ', true);
    });
}

But now, I fell in a pitfall for replacing orWhereHas in my query (because using it with %like% together causes very very slow response time.

Can you guys think of any way to replace/optimize orWhereHas?

change search able column

hi
i'm using persian language to search but i get this error:
SQLSTATE[HY000]: General error: 1271 Illegal mix of collations for operation 'like' (SQL: select count(*) as aggregate from posts where (id like %س% or title like %س% or created_at like %س%))

it because of search in created_at column
how can i change the searchable column or search query ???
i know i cant use {searchable:false} but it is laratables Additional Columns and i cant disable search for it

Relationship from Another Relatonship Table

Hello, I wanna ask. Is it possible to have relationship from another relationship table?
Let's say I have 3 tables: Table A, Table B, and Table C.
Table A related to Table B, and Table B related to Table C.
So, with that kind of relationship, it's possible for me to display Table B data on Table A, and display Table C data on Table B using Laratables.
Then, here comes my question. Is it possible to display Table C data on table A using Laratables?
Because Table A related to Table B, and Table B related to Table C.

Anyway, thanks a lot for creating Laratables. It helps me a lot. :)

Make a dediacted class for the tables

Hi,

How about making a class for the tables something like UsersTable that will contain the methods for extra columns and every other customization.
This will leave the model clean and avoid cluttering it with dataTable methods

Error after instalation

After install it, I received this error, do you know what can be?

PHP Parse error: syntax error, unexpected '=' in /var/www/vendor/freshbitsweb/laratables/src/helpers.php on line 46

The date format is not working

When I tried to show the createad_at column, it appeared like this [object Object].

I configured the format that I want, but it didn't appear.

Adding ordering doubles rendering time

When adding ordering on client JavaScript

var table = $('#clients-table').DataTable({
    serverSide: true,
    ajax:       '{!! action('ClientsController@managed_clientsfordatatable', ['partner_approved' => $partner_approved]) !!}',
    columns: [
        { name: 'checkforapprove', searchable: false, orderable: false },
        { name: 'id', searchable: true,  orderable: true  },
        ...
        { name: 'actions', searchable: false, orderable: false },
    ],
    'order': [[12, 'desc']]
});

render time doubles. I can set the ordering server side as well, but then how do I indicate current ordering column and direction?

P.S. Absolutely wonderful package! Works extremely easy and smooth and is still very powerful!!

Failed to Acces Relation

i have 3 relations

user ->hasOne->room
room->belongsTo->floor
floor->hasMany->room

{ name: 'id' },
{ name: 'name' },
{ name: 'email' },
{ name: 'action', orderable: false, searchable: false },
{ name: 'room.name', orderable: false },
{ name: "room.floor.level" } // this show [object Object] on the table

Selecting/Displaying a custom column

Hello.

I was wondering if there is a way to select a custom column to be displayed on Datatables.

In MySQL I currently have this statement, whereby I am selecting a column called additional, performing a conditional on it and aliasing it as downloaded_app:

SELECT IF (additional LIKE '%device_information%', 'Y', 'N') AS downloaded_app

In Eloquent I would do something along the lines of DB::raw('IF (...) AS downloaded_app')

I am just wondering how I could incorporate this custom column into Laratables.

At the moment I am receiving an unknown column error: Column not found: 1054 Unknown column 'downloaded_app' in 'field list'

Cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.