Laravel how to import excel/xls file into database

Sure, here are the steps to import an Excel file into Laravel:

  1. First, you need to install the "maatwebsite/excel" package using Composer. You can do this by running the following command in your terminal:

    composer require maatwebsite/excel

  2. Next, create a new controller or use an existing one to handle the file upload and import process.

  3. In your controller, you'll need to include the following classes at the top: 


use Maatwebsite\Excel\Facades\Excel;
use App\Imports\YourImportClass;



Create a function to handle the file upload and import process. This function should accept a file parameter and use the Excel class to read the file and pass it to your import class. Here's an example:

public function import(Request $request)
{
    $file = $request->file('file');

    Excel::import(new YourImportClass, $file);

    return redirect()->back()->with('success', 'File imported successfully!');
}



Create an import class to handle the actual import process. This class should extend the "Maatwebsite\Excel\Concerns\ToCollection" class and implement the "toArray()" method. This method should return an array of data that will be imported into your database. Here's an example:


use Maatwebsite\Excel\Concerns\ToCollection;

class YourImportClass implements ToCollection
{
    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            // process each row and save data to database
        }
    }
}




Finally, create a view with a form to allow users to upload the Excel file. The form should have an input field with the name "file" and the "enctype" attribute set to "multipart/form-data". Here's an example:


<form method="POST" action="{{ route('import') }}" enctype="multipart/form-data">
    @csrf
    <input type="file" name="file">
    <button type="submit">Import</button>
</form>



That's it! With these steps, you should now be able to import Excel files into your Laravel application.

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...