How to pass user_id for importing excel using Laravel?

1.6k views Asked by At

I have a problem with excel import using Laravel. The user wants import excel of suppliers data into database. The suppliers table got user_id but the user may not have their own user_id. So, when importing excel file the user use excel without user_id columns. So I want to pass the user_id of that user and stored in database.

SuppliersImportController

public function store(Request $request)
{
    $user_id = auth()->user()->id;        
    Excel::import(new SuppliersImport($user_id), request()->file('file'));

    return  redirect('/suppliers')->withStatus('Excel file imported successfully');
}

SuppliersImport

public function  __construct($user_id)
{

    $this->user_id =$user_id;
}
public function model(array $row)
{
    return new Supplier([
        'name' =>$row[0],
        'phone' =>$row[1],
        'email' =>$row[2],
        'address' =>$row[3],
        'city' =>$row[4],
        'country' =>$row[5],
        'customer' =>$row[6],
        'user_id'=> $this->user_id,         
        
    ]);

Error

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into suppliers (name, phone, email, address, city, country, customer, updated_at, created_at) values (soe, 176893848, [email protected], abc, Yangon, Myanmar, 1, 2020-11-27 12:15:08, 2020-11-27 12:15:08))

1

There are 1 answers

2
AnkitS On

So what you can do is

public function model(array $row)
{    
    $user = auth()->user();  //Get the current user 
    return new Supplier([
        'name' =>$row[0],
        'phone' =>$row[1],
        'email' =>$row[2],
        'address' =>$row[3],
        'city' =>$row[4],
        'country' =>$row[5],
        'customer' =>$row[6],
        'user_id'=> $user->id,      // add their user id when importing    
        
    ]);