2

I am using the Maatwebsite/excel component to import excel files. In this case, importing users. I need to validate that the mail does not exist and then import the unique data

I have this code in the import file

namespace App\Imports;

use App\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;

use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;

class UsersImport implements ToModel, WithValidation
{
    use Importable;
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $user = User::create([
            'name'     => $row[0],
            'email'    => $row[1], 
            'password' => Hash::make($row[2]),
        ]);

        $user->assignRole('guest');
    }

    public function rules(): array
    {
        return [
            '0' => 'required|string',
            '1' => 'unique:users',
        ];
    }

}

And this code in my controller:

public function import() 
{
    Excel::import(new UsersImport, request()->file('file'));

    return back()->with('success', 'Importado con éxito!');
}

When I want to import duplicate data, I get the following error

SQLSTATE[42S22]: Column not found: 1054 Unknown column '1.1' in 'where clause' (SQL: select count(*) as aggregate from users where 1.1 = [email protected])

1

2 Answers 2

5

The validator's exist rule will use the key of the array (1 in your case) as the column to search inside the users table.

You can specify the column like this and it should work.

'1' => 'unique:users,email',

From: https://laravel.com/docs/5.8/validation#rule-exists

Sign up to request clarification or add additional context in comments.

1 Comment

Excelent! that was
0

I found the solution for my question

namespace App\Imports;

use App\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;

use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;

class UsersImport implements ToModel, WithValidation
{
    use Importable;
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
public function rules(): array
{
    return [
        '1' => 'unique:users,email'
    ];

}

public function customValidationMessages()
{
    return [
        '1.unique' => 'Correo ya esta en uso.',
    ];
}

public function model(array $row)
{
    $user = User::create([
        'name'     => $row[0],
        'email'    => $row[1], 
        'password' => Hash::make($row[2]),
    ]);

    $user->assignRole('guest');
}


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.