Search code examples
laravelcsvlaravel-excel

How do I combine csv data and other data collected in the app laravel excel


I have a csv file that holds pins. Every time I upload the file and try save the other data collected in the app it doesn't group and add them all together

This is my code please help!

//import pins & save additional data
    public function importPins(Request $request)
    {
        //save the records
        $pins = new Pins([
            'rewardName' => 'Game Gateway',
            'rewardId' => '1',
            'username' => 'Admin'
        ]);
        Excel::import(new PinsImport, request()->file('csv_file'));
        $pins->save();
        return back()->with('success', 'Pins Imported successfully.');
    }

//Pins Import class
<?php

namespace App\Imports;

use App\Pins;
use Maatwebsite\Excel\Concerns\ToModel;

class PinsImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new Pins([
            'voucherPin' => $row[0]
        ]);
    }
}

Solution

  • You can try to pass in the attributes you want to use to create the models into the Import class.

    class PinsImport ...
    {
        protected $attributes = [];
    
        public function __construct($attributes = [])
        {
            $this->attributes = $attributes;
        }
    
        public function model(array $row)
        {
            return new Pins([
                'voucherPin' => $row[0]
            ] + $this->attributes);
        }
    }
    
    
    $attributes = [
        'rewardName' => 'Game Gateway',
        'rewardId' => '1',
        'username' => 'Admin'
    ];
    
    Excel::import(new PinsImport($attributes), request()->file('csv_file'));