'Import from Excel to Database with Relationship in Laravel

I want to make excel import the data I imported has relational values ​​to another table. so, when i import excel it will save the data in one tables. below are the relationship tables that I have

siswas table

  • id
  • nis

nilais table

  • id
  • siswa_id
  • nilai

and below are the codes that I have made in the controller, view and import files. View Form

<form action="{{ route('nilai.import')}}" method="POST" enctype="multipart/form-data">
@csrf
<div class="form-group">
    <label for="name">Name</label>
    <input name="name" type="text" class="form-control" required>
</div>
<div class="form-group">
    <label for="file">File</label>
    <input name="file" type="file" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Import</button>

Controller :

public function store_import_keterampilan(Request $request)
{
    Excel::import(new NilaiMapelKeterampilanImport(), $request->file('import_file'));
    return redirect('/nilai')->with(['message'=> 'Data Berhasil di Import!!']);
}

Import Class

Cass NilaiMapelKeterampilanImport implements ToModel, WithHeadingRow

{ use Importable;

protected 
public function __construct()
{
  
}
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
    $siswa = Siswa::where('nis', $row['nis'])->first();

    return new NilaiKeterampilan([
        'siswa_id'      => $siswa->id,
        'npj_ns'        => $row['npj_ns'],
    ]);
}

}

How do I set the value to take the siswa id so that it can be inserted in the value table? because for now, if I take $siswa->id and insert it into the table the value always error Trying to get property 'id' of non-object on $siswa->id, but $siswa is not null and i can get the data enter image description here

Thanks for your time.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source