samedi 6 mars 2021

Cannot import excel data in database

I want to import data from excel file to mysql database table using Laravel Excel package Link : https://laravel-excel.com/

used below code

 if($request->hasFile('sample_file')){
       $path = $request->file('sample_file')->getRealPath();
       try {
       $products=\Excel::import(new ImportProductItems, request()->file('sample_file'));
       } catch (\Illuminate\Database\QueryException $e) {
  }

Imports Model :

 <?php
    
    namespace App\Imports;
    
    use App\Models\ProductItems;
    use Maatwebsite\Excel\Concerns\ToModel;
    use Maatwebsite\Excel\Concerns\WithHeadingRow;
    use Arr;
    
    class ImportProductItems implements ToModel, WithHeadingRow
    {
        /**
        * @param array $row
        *
        * @return \Illuminate\Database\Eloquent\Model|null
        */
        public function model(array $row)
        { 
            return new ProductItems([
                'product_id'     => $row['product_id'],
                'product_name'    => $row['product_name'],
            ]);
        }
    }

Model:

<?php

namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;

class ProductItems extends Model
{
    protected $table = "product_items";

    protected $fillable = [
       'product_id','product_name'
    ];

    
}

when i import excel file no row gets inserted in the database and i'm not getting any error. Any help is highly appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire