How to allow models with belongsToMany relationship to be searchable using datatables?

  datatables, javascript, laravel, php

I have the following model that has a belongsToMany relationship:

class Sale extends Model
{
    public function items()
    {
        return $this->belongsToMany(Item::class)->select(
            [DB::raw("COUNT(*) as quantity"), 
            DB::raw("CONCAT('(', GROUP_CONCAT(serial_number SEPARATOR ', '), ')') AS serial_number"),
            'items.name', 
            'items.upc',
            'items.id',
            'items.with_serial_number', 
            'items.selling_price', 
            'item_sale.sold_price',
            'item_sale.item_purchase_id'])
        ->join('item_purchase', 'item_sale.item_purchase_id', '=', 'item_purchase.id')
        ->orderBy('item_sale.id', 'ASC')
        ->groupBy('item_sale.item_id', 'item_sale.sale_id');
    }

and on my controller

public function demo(Request $request)
    {
        if ($request->ajax()) {
            $data = Sale::with(['branch', 'items', 'customer', 'user'])->select(['*']);

            return Datatables::of($data)
                    ->addIndexColumn()
                    ->make(true);
        }
    }

and on my jquery

$('#search_sale_list').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "{{ route('rma.demo') }}",
        "columns": [
            {data: 'created_at'},
            {data: 'branch.address'},
            {data: 'sale_number'},
            {data: 'items'}
        ]
    });

My problem is i cant seem to call the ‘items’ in my view when i use the searchbox of datatables, it gives out an error. is this even possible to do using datatables?

Source: Laravel

Leave a Reply