afujita's avatar

Laravel Excel: save filename into database

Hi. Using maatwebsite plugin to import csv file data into database. It is a stupid question, but how can I save also the filename?

Here is what I am using:

$file = Input::file('csv_file');
Excel::filter('chunk')
            ->load($file->getRealPath())
            ->chunk(250, function($results) {
                foreach($results as $row)
                {
                    $sales = Sale::create([
                        'company_code' => $row->xxxx,
                    'sale_year_month' => $row->xxxx, 
                    'sale_date' => $row->xxxx
                    ]);
                }
            });
    return Redirect::to('/');

I tried to use this after the file upload:

$sales->csv_file = $destinationPath.'/'.$name;
$sales>save();

But it created a new extra record with just the filename path.

Thank you.

0 likes
7 replies
afujita's avatar

Thanks @tomi, for your reply. In my case, I am just importing the csv file. Seems useful when exporting xls, am I wrong?

pmall's avatar

$file->getClientOriginalName()

afujita's avatar

Thanks for your help, @pmall! I can get the filename from your suggested code, or from the getRealPath, but what I am not able to do at this moment is how to insert the filename (inside csv_file column of db) together with the other row records (company_code, sale_year_month....). Sorry for not being clear. I can insert them independently (company_code, sale_year_month... from csv_file), but not together in the same row id.

pmall's avatar

Why can you just add a column and put the filename in this?

afujita's avatar

You mean inside the csv file? That would be good if I had few files, but actually I need to upload hundred of files, and each file has like 25000 rows.

pmall's avatar

I dont understand the problem. You have the name of the uploaded file, what prevents you from adding it with each rows?

afujita's avatar

Inserted the $filename inside foreach loop, before the create method, and everything went OK! Thanks @pmall .

Please or to participate in this conversation.