code-8
code-8

Reputation: 58662

orderBy in Laravel + jquery datatables

In my database, here is what I have

enter image description here

I've tried to query everything and order by price

$service_plans = DB::table('service_plans') ->orderBy('price', 'asc') ->get();

I kept getting

enter image description here

Did I miss anything or did anything that I'm not suppose to here ?

Any hints ?

P.S. Keep in mind that I'm using jQuery DataTables

Upvotes: 2

Views: 23979

Answers (4)

Arfan
Arfan

Reputation: 169

You still get that data because of the datatables does ordering your data as well, so your orderBy query isn't work. Just set to your parameter datatable ordering: false to make it works.

$('#datatable').DataTable({
    ordering: false, //disable ordering datatable
});

so, you can sort your data by whatever fields you want althought you dont want to show them in your table.

Upvotes: 3

num8er
num8er

Reputation: 19372

Type of price field is string so change it to decimal with 2 numbers after comma.

Run in mysql console:

ALTER TABLE service_plans MODIFY price DECIMAL(10,2);

!!! When making modification on tables on production make sure that You've copy of table before calling ALTER TABLE:

CREATE TABLE service_plans_bak AS SELECT * FROM service_plans;

Upvotes: -2

Mike Barwick
Mike Barwick

Reputation: 5367

Since you're using Datatables jQuery plug-in, remove the orderBy in your controller query.

Instead, sort via datatables (which will do so by default):

$('#datatable').DataTable({
    "order": [[ 2, "asc" ]] // Order on init. # is the column, starting at 0
});

There's also a nice little Laravel package for datatables that will set the data. Check it and see if it'd be useful: https://github.com/yajra/laravel-datatables

Upvotes: 16

swatkins
swatkins

Reputation: 13630

You can add a $casts property to your ServicePlan model. This will treat the column as the implicit data type regardless of the database data type.

class ServicePlan extends Model
{
    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'price' => 'integer',
    ];
}

https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting

Upvotes: -2

Related Questions