Search code examples
phplaravelconstructorlaravel-excel

Too few arguments to function App\Exports\NilaiExport::__construct(), 0 passed in NilaiController.php on line 112 and exactly 1 expected


I want to export data to excel from $id, but an error occurred when I added the constructor in App/Export/NilaiExport. thanks

NilaiController.php

function download($id){

    return Excel::download(new NilaiExport, 'Nilai.xlsx');
    }

NilaiExport.php

<?php

namespace App\Exports;

use App\Khs;
use Maatwebsite\Excel\Concerns\FromCollection;

class NilaiExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    protected $id;

    public function __construct($id) {
    $this->id = $id;
    }

    public function collection()
    {
        return Khs::findOrFail($this->id);
    }
}

Solution

  • function download($id){
        return Excel::download(new NilaiExport($id), 'Nilai.xlsx');
    }
    

    You need to pass through the id variable to the constructor method, it does say in the error message that it expects 1 parameter but you didn't supply one.

    If the parameter is optional then the constructor signature should look something like this

    public function __construct($id = null) {
        $this->id = $id;
    }
    

    and you would define id as

    /**
     * @var \Illuminate\Support\Collection|null
     */
    protected $id;