How to read file without import to database using Maatwebsite library laravel excel

Hi,

if your are using https://laravel-excel.com/ Library to import excel files from your local, and your want to only read it and to return it as Array.

FOLLOW this Tutorial

For example :

This is your controller

//Get your request
$excel = $request->file('excel_file');
// default importation from the documentation of the library ;
$array = Excel::import(new ProductsImport, $excel);

your model import is :

<?php

namespace App\Imports;

use App\Models\Coli;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ColiImport implements ToModel, WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Coli([
« name » => $row[‘destinataire’],
« phone » => $row[‘telephone’]
]);

}

}

And your model is :

PS : Don’t forget to fill your fields in your model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Coli extends Model
{
protected $fillable= [‘name’,’address’,’phone’];
protected $table = ‘colis’;
use HasFactory;
}

SOLUTION :

In your controller USE this code

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

instead of : $array = Excel::import(new ProductsImport, $excel);

HOW this article will help you

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>