-2

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);
    }
}
aynber
  • 22,380
  • 8
  • 50
  • 63
Tammam
  • 416
  • 1
  • 7
  • 16
  • 1
    I suppose it is `new NilaiExport($id)` And you should start to __understand__ what error text tells you. – u_mulder Jun 27 '19 at 13:53
  • I tried it but the page was not accessible ("Sorry, the page you are looking for could not be found.") – Tammam Jun 27 '19 at 14:00
  • Probably you need to understand how to read an error message (and a bit of object-oriented programming) – mordack550 Jun 27 '19 at 15:30

2 Answers2

2
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;
Harry10932
  • 36
  • 5
0

You have used the constructor inside the NilaiExport class, but you do not pass the parameter class when creating the object, you can use the following code. use blew

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

instead of this

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