Laravel-datatables: yajra Datatables quick search function not searching

Created on 7 Jun 2016  ·  17Comments  ·  Source: yajra/laravel-datatables

Good Day!

I am having a problem with the searching of records in my datatables. Only the tracking_id column can be searched. I need all of the columns to be searched.

Here is my query php code:

$result = Document::join('user','document.user_id','=','user.id')
->join('classification','document.classification_id','=','classification.id')
->select('document.id',DB::raw('CONCAT(document.tracking_type,"-",document.tracking_date,"-",document.tracking_seq_no) AS tracking_id'),'document.date_prepared','document.subject','classification.description as doc_class')
->orderBy('document.created_at','desc')->get();

return Datatables::collection($result)
->addColumn('check',function($record){
    return '<input type="checkbox" name="check['.$record->id.']" class="checkboxes" value='.$record->id.'>';})
->addColumn('action',function($record){
    return '<a href="/records/view/' . $record->tracking_id . '">View Record</a></a>';})
->addColumn('document.tracking_id',function($record){
    return $record->tracking_id;})
->editColumn('document.doc_class',function($record){
    return $record->doc_class;})
->addColumn('document.subject',function($record){
    return $record->subject;})
->addColumn('document.date_prepared',function($record){
    return date('F d, Y', strtotime($record->date_prepared));})
->make(true);

JS Declaration:

docstable = $('.docstable').DataTable({
    processing: true,
    serverSide: true,
    ajax: "/ajax/docrec"
    columnDefs: [
        {targets:[0,1], orderable:false}
    ],
    columns: [
        {data:'check'},
        {data:'action'},
        {data:'tracking_id',name:'document.tracking_id'},
        {data:'doc_class',name:'document.doc_class'},
        {data:'subject',name:'document.subject'},
        {data:'date_prepared',name:'document.date_prepared'}
    ]
});

Is there a way like Bllim Datatables that can search all specified columns by using searchColumns() in php code? Thank you

question

Most helpful comment

Hi @ChaosPower and thanks a lot for your answer.

I tried your solution but it didn't worked. Actually $this->mainRepo->model is my model instance, from App\Models. It is binded to the mainRepo stuff but it's not related to my problem.
I updated to have something like this (from my repository) :
$query = $this->model->with($with);
$dataTable ?: $query->orderBy($orderBy, $sort);
return !$dataTable ? $query->get($columns) : $query->select($columns);

I use this method to manage all DataTables data from my models. If the dataTable variable is false, no ordering is applyed, and i use a select('*').

In the end, the chained method could look like :
$this->model->with('relation')->select('*'); where $this->model is App\Models\User.

The column ordering is now working perfectly, but the default text search have still no effect on the search. All results are displayed not depending my input.
Did i done something wrong again ?

We see here my search input, but all of my 3 users are returned, even if the 'my search value' input should return nothing at all.
capture

Thx a lot for your help

All 17 comments

Quick search in all columns are supported by default but since you are using join queries, there are some changes on how you have to declare the name on your script like on this demo.

BTW, why are using collection instead of eloquent? I suggest you remove get() on your query and use return Datatables::eloquent($result) instead?

Hello !
To me, the global search is always returning a empty result. My datatable is empty after search. Filled up with all data when i remove all search inputs.
But i do it as simple as :
$users = $this->mainRepo->model->get(); return Datatables::of($users)->make(true);

I can see in the HTTP request my search input, but row result is always empty. Do i need to do something server-side to allow global search options ? I thought it was automatic...
capture

Datas are comming from my Repository wih basicly do a $model->get() without any any ordering/sorting. I thought it was enough to make some global and column text filtering. But do i need to implement solution to use a 'where' in my Eloquent request ? Or is it better filter using DataTables filter method ? (In case of nothing is automatic, and i need to do all server-side).

But this example and this one do not implement any server-side processing, and get a global search, even per column search... I tried all those examples, without success : search result is always empty, datatable is empty at first search character submit, and back filled with all data when no filter at all is filled...

Basic questions is : Is there anything implemented in the package for server-side filtering/searching from Model Datas, or is there only column sorting & pagination that are available ?

Thanks a lot for your reading, and your help !

PS: linked to my #562 comment

@mtx-z when you invoke ->get() you are using collections instead of LDT's object.

$users = User::select(['id', 'name', 'email', 'password', 'created_at', 'updated_at']); //Eloquent Object

$users->all(); // Collection

Laravel Datatables automatically does ->get() and I advice you do not use ->get() when you

return Datatables::of($users)->make(true);

Based on your example you do not need ->get()


$users = $this->mainRepo->model->get(); return Datatables::of($users)->make(true);

just


$users = $this->mainRepo->model; return Datatables::of($users)->make(true);

For your main question regarding filtering and searching. Laravel Datatables already implements searching to all columns by default / server side processing. And also supports individual column filtering.

https://datatables.yajrabox.com/eloquent/basic - see headers transmitted
https://datatables.yajrabox.com/eloquent/multi-filter-select - see headers transmitted

Hi @ChaosPower and thanks a lot for your answer.

I tried your solution but it didn't worked. Actually $this->mainRepo->model is my model instance, from App\Models. It is binded to the mainRepo stuff but it's not related to my problem.
I updated to have something like this (from my repository) :
$query = $this->model->with($with);
$dataTable ?: $query->orderBy($orderBy, $sort);
return !$dataTable ? $query->get($columns) : $query->select($columns);

I use this method to manage all DataTables data from my models. If the dataTable variable is false, no ordering is applyed, and i use a select('*').

In the end, the chained method could look like :
$this->model->with('relation')->select('*'); where $this->model is App\Models\User.

The column ordering is now working perfectly, but the default text search have still no effect on the search. All results are displayed not depending my input.
Did i done something wrong again ?

We see here my search input, but all of my 3 users are returned, even if the 'my search value' input should return nothing at all.
capture

Thx a lot for your help

I finally did it :) ty

I also suddenly cannot search relation, I used $this->model->with('relation')->select('*');
mtx-z can you share the solution ?

Hey. The code I used was specific to me.
The this->model contain an instance of my model.

Can you provide your code?

\\ In controller
$result = MsCustomer::with('company')->select('ms_customers.*');
return Datatables::of($result)->make(true);

\\ In view
$('#data-table').DataTable({
    ajax: '{!! route('master.customer.data') !!}',
    columns: [
        { data: 'id', name: 'id' },
        { data: 'code', name: 'code' },
        { data: 'name', name: 'name' },
        { data: 'email', name: 'email' },
        { data: 'company.name', name: 'company.name' },
   ]
});

Datatables run and display data include the relation company.name, but cannot search the relation. I guess, the code already similar like this demo

I have model MsCustomer with declare protected $table = 'ms_customers', also relation 'company' inside MsCustomer model. Then MsCompany model with table name 'ms_companies'.

I can search id, code, name, and email, but not the relation 'company.name'. There is something wrong with above code ?

I have the same problem with @maengkom, my table loaded fine. but when i search the result always empty

in Controller

$agenda = AgendaMasuk::with('surat')
            ->whereNotNull('surat_id')->where('group_id', $group->id)
            ->select('agenda_masuks.*');
        return Datatables::of($agenda)->make(true);

in view

var table = $('#surats').DataTable({
        "jQueryUI"   : true,
        "paging"     : true,
        "lengthMenu" : [ 5, 10, 25, 50, 75, 100, "All" ],
        "autoWidth"  : false,
        "stateSave"  : false,
        "order"      : [[ 0, 'asc' ]],
        "processing" : true,
        "scrollX"    : true,
        "serverSide" : true,
        "ajax": {
            "url": $('#surats').data('url'),
            "type": "POST"
        },
        "columns": [
            {
                className: 'text-center',
                data: 'no_agenda',
                name: 'agenda_masuks.no_agenda'
            },
            {
                className: 'text-center',
                data: 'surat.no_surat',
                name: 'surat.no_surat'
            },
            {
                className: 'text-center',
                data: 'tanggal',
                name: 'agenda_masuks.tanggal'
            },
            {
                data: 'surat.sifat',
                name: 'surat.sifat',
                sortable: false
            },
            {
                data: 'surat.pengirim',
                name: 'surat.pengirim'
            },
            {
                data: 'surat.tujuan',
                name: 'surat.tujuan'
            },
            {
                data: 'surat.ringkasan',
                name: 'surat.ringkasan',
                sortable: false
            },
            {
                data: null,
                defaultContent: '-',
                name: 'disposisi',
                searchable: false,
                sortable: false
            },
            {
                data: null,
                defaultContent: '-',
                name: 'file',
                searchable: false,
                sortable: false
            }
        ]
    });

@maengkom I have the same problem, i was not able to use the global search on object values AND relation values (only the id).
For example, all of my models have a "translation_model" associated. Wich contain the public text and only it. Well, my datatable cannot automaticaly search the name of the translations.

To fix that, i edited the ajax call to add some parameter (text search, select value...) and I use this values to filter the eloquent query before sending it to Datatable.
From here, you can filter on anything (for the actual case, it's a "where" with a "whereas translation" where "translations.name='search_value'" as it is eloquent.

@nsetyo have you checked the returned collection ? Does the data in the collection match what datatable needs ?

@mtx-z yes it does. i temporary fix this with using join queries instead

@nsetyo @mtx-z the owner already confirmed the search relation still has a bug. check this out https://github.com/yajra/laravel-datatables/issues/698

I'm trying help to fix it and still learning the code in filtering method inside the package but still confuse where should be fixed 😆

All of my search fields are functioning now but I have 1 problem left. Based on the given demo by yajra (Owner), there is Created At & Updated At field in the table. I also have a field in my table displaying date and time but the thing is, if I formatted the displayed date and time to a much readable for users, the the datatable was unable to search those newly formatted date and time.

Example: (Default Date and Time format displayed)
2016-08-23 14:37:25

I formatted that into:
AUGUST 23, 2016 02:37:25 PM

using date('F d, Y h:i:s a',strtotime($the_given_date_and_time));

After formatting, the datatable was unable to search that field

You can use filterColumn api to override the default sql for searching on date column to match on what was displayed .

For addcolumn, it should be searchable.

Was this page helpful?
0 / 5 - 0 ratings