Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel excel read file without import to database

Tags:

php

laravel

I'm using this libray to manage excel file on laravel project (https://docs.laravel-excel.com/3.1/getting-started/)

I would like to readonly excel file once I upload in from local and return as JSON.

My code in controller is

$excel = $request->file('excel');
$array = Excel::import(new ProductsImport, $excel);

where ProductsImport file is

<?php

namespace App\Imports;

use App\Models\Product;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;

class ProductsImport implements ToModel
{

    use Importable;

    /**
     * @param array $row
     *
     * @return Products|null
     */
    public function model(array $row)
    {

        //return $row;

        return new Product([
            'name' => $row[0],
            'email' => $row[1]
        ]);

    }
}
like image 222
Giffary Avatar asked Jul 02 '19 06:07

Giffary


2 Answers

you can try this solution:

$theArray = Excel::toArray([], 'myexcelfile.xlsx');

$theArray contains the content of the 'myexcelfile.xlsx' file. in order to skip adding the content of the excel file to the database you can use [] instead of the ProductsImport object.

like image 162
Hadi Nahavandi Avatar answered Nov 14 '22 19:11

Hadi Nahavandi


Thx to Hadi for pointing us in the right direction. Here are some working examples based on importing a csv file using the usual file input. In my case, once uploaded the file is accessible through the request object as 'csv_file'.

public function importCSV(Request $request)
{
    // Get the csv rows as an array
    $theArray = Excel::toArray(new stdClass(), $request->file('csv_file'));

    // Get the csv rows as a collection
    $theCollection = Excel::toCollection(collect([]), $request->file('csv_file'));

    //etc
}
like image 33
omarjebari Avatar answered Nov 14 '22 18:11

omarjebari