Search code examples
phpexcellaravellaravel-excel

Possible to add multiple parameters to excel import?


I have a basic form that contains an excel file upload and a select option.

The select contains a few options. I want to pass the selected option from the user with the file to my Excel::import

I tried passing another parameter to my import but it returns error. (has to be string, array given)

Is this possible using Laravel excel import?

Controller

public function create(Request $request)
{
    if($request->hasFile('file')) 
    {
        $package = $request->input('package');
        // how can I add $package to my import to insert it to my user model?
        Excel::import(new AccountsImport, $request->file('file'));

        return ['message' => 'Excel has been succesfully uploaded'];
    }
}

AccountsImport

class AccountsImport implements ToCollection, withHeadingRow
{

    public function collection(Collection $rows)
    {
        $rows->each(function($row, $key) {
            Account::create([
                'name'   => $row['student'],
                'email'  => $row['e_mail'],
                // Want it to be possible to add my package here
                //'package' => $package
            ]);
        });
    }
}

Solution

  • Maybe you could pass down custom data to your AccountsImport class?

    You would have a data array as such:

    $data = [
        'package' => $package, 
        // other data here
    ]; 
    

    You would then do something like this:

    Excel::import(new AccountsImport($data), $request->file('file'));
    

    That would require some changes in your import class.

    class AccountsImport implements ToCollection, withHeadingRow
    {
        private $data; 
    
        public function __construct(array $data = [])
        {
            $this->data = $data; 
        }
    
        public function collection(Collection $rows)
        {
            $rows->each(function($row, $key) {
                Account::create(array_merge([
                    'name'   => $row['student'],
                    'email'  => $row['e_mail'],
                    // Want it to be possible to add my package here
                    //'package' => $package
                ], $this->data));
            });
        }
    }
    

    I took a look at Laravel Excel's API and couldn't see something that would cater for this, but this should work.