0

Im building my first laravel website, and try to setup Maatwebsite\laravel-excel package

the form value from the view already passed to controller variable. and now im setting the Model using FromQuery and WithMapping.

but i got problem when try to foreach inside return

IndustriesExport.php

<?php

namespace App\Exports;

use App\Industry;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;


public function map($industry): array
    {

//these things can't work        
        return [
            foreach ($columns as $column) {
               '$industry'->column,
            }
        ];


//expecting foreach to be like this
        return [
            $industry->id,
            $industry->name,
            //and so on.
        ];


    }

IndustriesController.php

public function exportTerpilih(Request $request) 
    {
//these things are from checkbox
        $id = $request->input('id');
        $column = $request->input('columns');                
    }

i just want to make custom export table, i will appreciate any solution :)

~sorry for bad english

Mafaza SP
  • 81
  • 7
  • don't use the foreach inside the return. you initialize an array, build the contents using foreach, then finally use return – Kevin May 02 '19 at 06:33

2 Answers2

4

You cannot do functions in a array, you should return the following

$return = [];
foreach($columns as $column) {
    $return[$column]=$industry[$column];
}
return $return;
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
1

You can use map() function of laravel collection.

return collect($columns)->map(function ($column) use ($industry) {
    $industry[$column];
})->toArray();
Tharaka Dilshan
  • 4,371
  • 3
  • 14
  • 28