Laravel-datatables: Order table column in view return null value for two tables has same column name

Created on 24 Jan 2020  路  3Comments  路  Source: yajra/laravel-datatables

Summary of problem or feature request

When press in view order column has relation with another table will return null value
for same column name from joined table.
if call to another table has same column name for example
Table Category has title column Category.title
Table Product has title column Product.title
in view product we load basic product model with category table
when order in category_id make null value from another table to title

Code snippet of problem

 public function query(Task $model)
    {
        return $model->newQuery()->with('product');
    }
 protected function getColumns()
    {
        return [
            'title',
     //            'product_id'
            'product_title' => new \Yajra\DataTables\Html\Column([
                'title' => 'Product',
                'data' => 'product.title',
                'name' => 'product.title'
            ]),
        ];
    }

System details

  • Operating System xampp
  • PHP Version 7.3
  • Laravel Version 6.0
  • Laravel-Datatables Version latest
question

All 3 comments

I'm not sure I fully understand the question, but I think you might need to write your own filterColumn() method for columns with relations.

Here is an example:

/**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->filterColumn('product.table', function ($query, $keyword) {
                $query->whereHas('product', function ($subquery) use ($keyword) {
                    $subquery->where('title', 'like', '%' . $keyword . '%');
                });
            });
    }

This is untested, but should give you the general idea.

Just realized your question was about ordering, not filtering. The same answer applies, but using orderColumn() instead of filterColumn()

I think you just need to fix your columns.

@RyanPriceDotCa suggestions should work too but the package can do the same without leveraging filterColumn or orderColumn for simple relationships.

public function query(Task $model)
    {
        return $model->newQuery()->select('tasks.*')->with('product');
    }
 protected function getColumns()
    {
        return [
            Column::make('title'),
            Column::make('product.title')->title('Product'),
        ];
    }
Was this page helpful?
5 / 5 - 1 ratings