vandan's avatar
Level 13

Call to a member function toArray() on array

when i import csv file then not import duplicate email so i want some validation in import file but error

here is my code

<?php

namespace App\Imports;

use App\Library;
use Maatwebsite\Excel\Concerns\ToModel;
use Illuminate\Support\Facades\Validator;

class libraryImport implements ToModel
{
        /**
        * @param array $row
        *
        * @return \Illuminate\Database\Eloquent\Model|null
        */
        public function model(array $row)
        {
            Validator::make($row->toArray(), [
                    '*.2' => 'required|email|unique:libraries,mail',
            ])->validate();

            return new Library([
                'id'        => $row[0],
                'name'      => $row[1],
                'mail'      => $row[2],
                'owner'     => $row[3],
                'contact_no' => $row[4],
                'address'   => $row[5],
                'status'    => $row[6],
                // 'password' => \Hash::make('123456'),
            ]);
        }
}
0 likes
6 replies
Sinnbeck's avatar

You are defining that you are getting an array here

model(array $row)

And then try to change it to an array here

$row->toArray()

You cannot change an array to an array

1 like
Nakov's avatar
Nakov
Best Answer
Level 73

The error is pretty straight forward isn't it?

public function model(array $row)

You are passing array, and you try toArray() on it..

Use just this maybe:

 Validator::make($row, [
                    '*.2' => 'required|email|unique:libraries,mail',
            ])->validate();
1 like
Nakov's avatar

@van1310 I don't think you can use the laravel validation like that, this *.2 doesn't seem right to me, I might be wrong..

You can try this instead?

if( ! isset($row[2]) && ! filter_var($row[2], FILTER_VALIDATE_EMAIL) )
{
   return; // skip this row
}

// ... rest of your code here that returns a library
1 like
Nakov's avatar

@van1310 and after this check, you can check as well if the mail has already been used.. I missed that part in my previous answer..

so add this guard as well:

if (Library::whereMail($row[2])->first())
{
   return; // again skip this row.
}   
1 like

Please or to participate in this conversation.