Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Syed1980's avatar

How can I add a variable to this array while exporting excel in laravel application?

Hello folks, below is my collection function for excel export, please have a look and suggest me how can I add the variable in the first column or how can I trim the first row result after the fetch?

Everything works fine in the excel export, but only thing I want is to replace the first column with variable or trim the "$order_unq_id" from this "MH-Ord/171222/12843/XYZ Supermarket" to just the name like this "XYZ Supermarket". Thanks for your time.

    public function collection(){
    $order_unq_id = request()->session()->get('order_unq_id');
    $val = $order_unq_id['order_unq_id'];

     $orderDtls = DB::table('ordersmht')
     ->select(
         'ordersmht.order_unq_id',  // I want this to be trim or a variable on this place instead.
         'ordersmht.item_no_input',
         'ordersmht.supplier_barcode_input',
         'ordersmht.item_name_input',
         'ordersmht.item_unit_measure_input',
         'ordersmht.item_quantity',
         'ordersmht.item_cost_input',)
         ->where('ordersmht.order_unq_id', $val)
         ->paginate(500);     

         dd($orderDtls[0]);

         return $orderDtls;
	}

If I dd() this it give me result like this.

	{#3655 ▼
     +"order_unq_id": "MH-Ord/171222/12843/XYZ Supermarket"
    +"item_no_input": "4050E"
    +"supplier_barcode_input": "10001708018"
    +"item_name_input": "DOORMAT 4050E"
    +"item_unit_measure_input": "pcs"
    +"item_quantity": "1"
    +"item_cost_input": "4.00"
  }
0 likes
2 replies
MohamedTammam's avatar
Level 51

You can use map.

$orderDtls = DB::table('ordersmht')
     ->select(
         'ordersmht.order_unq_id',  // I want this to be trim or a variable on this place instead.
         'ordersmht.item_no_input',
         'ordersmht.supplier_barcode_input',
         'ordersmht.item_name_input',
         'ordersmht.item_unit_measure_input',
         'ordersmht.item_quantity',
         'ordersmht.item_cost_input',)
->where('ordersmht.order_unq_id', $val)
->paginate(500)
->map(fn($row) => [
	'your_new_variable' => 'your value for it',
	'item_no_input' => $row->item_no_input,
	'supplier_barcode_input' => $row->supplier_barcode_input,
	'item_name_input' => $row->item_name_input,
	 'item_unit_measure_input' => $row->item_unit_measure_input,
	 'item_quantity' => $row->item_quantity,
	 'item_cost_input' => $row->item_cost_input,
]);

if you need more logic, just loop over all data and change it then store it in a new array.

1 like

Please or to participate in this conversation.