PHPackages                             redsquirrelstudio/laravel-backpack-import-operation - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. redsquirrelstudio/laravel-backpack-import-operation

ActiveLibrary

redsquirrelstudio/laravel-backpack-import-operation
===================================================

An operation to make configurable imports for your CRUDs using the Backpack api you know and love

1.6.8(2y ago)1912.6k↓37.2%8[4 issues](https://github.com/redsquirrelstudio/laravel-backpack-import-operation/issues)MITPHP

Since Jul 8Pushed 2y ago1 watchersCompare

[ Source](https://github.com/redsquirrelstudio/laravel-backpack-import-operation)[ Packagist](https://packagist.org/packages/redsquirrelstudio/laravel-backpack-import-operation)[ RSS](/packages/redsquirrelstudio-laravel-backpack-import-operation/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (21)Used By (0)

Import Operation for Backpack for Laravel
=========================================

[](#import-operation-for-backpack-for-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/291280f87e70c6bbfb9146a0c947262992a8ea1234d4c2cfc92afb0b2bfdf404/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726564737175697272656c73747564696f2f6c61726176656c2d6261636b7061636b2d696d706f72742d6f7065726174696f6e3f7374796c653d666c61742d737175617265)](https://packagist.org/packages/redsquirrelstudio/laravel-backpack-import-operation)

[![Total Downloads](https://camo.githubusercontent.com/d41aa6624dc8dc0286fa941c2135ac98d5d818a2239b1e4c0ae7ab248fce2339/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f726564737175697272656c73747564696f2f6c61726176656c2d6261636b7061636b2d696d706f72742d6f7065726174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/redsquirrelstudio/laravel-backpack-import-operation)

Adds a configurable interface that allows your admin users to:

- Upload a spreadsheet file.
- Map the file's columns to your CRUD model's fields.
- Import their data.

and allows you as the developer to:

- Customise each CRUD's import behaviour using the Backpack API you know and love.
- Choose between queued or instant imports.
- Completely customise the operation's behaviour.

[!["Buy Me A Coffee"](https://camo.githubusercontent.com/9f44ce2dc3b3eecdd02598900866ffc518801df1932849703dae1e5ce5031070/68747470733a2f2f7777772e6275796d6561636f666665652e636f6d2f6173736574732f696d672f637573746f6d5f696d616765732f6f72616e67655f696d672e706e67)](https://www.buymeacoffee.com/redsquirrelstudio)

If you're looking for a great team of developers to handle some Backpack/Laravel development for you, drop us a line at [Sprechen](https://sprechen.co.uk)

**Also need full exports for your CRUD? Check out [redsquirrelstudio/laravel-backpack-export-operation](https://github.com/redsquirrelstudio/laravel-backpack-export-operation)**

[![Screenshot of the operation's mapping screen](https://raw.githubusercontent.com/redsquirrelstudio/laravel-backpack-import-operation/dev/assets/screenshot.jpg?raw=true)](https://raw.githubusercontent.com/redsquirrelstudio/laravel-backpack-import-operation/dev/assets/screenshot.jpg?raw=true)

Powering the imports in the background is [`maatwebsite/excel`](https://laravel-excel.com)and if you wish, you can define your own import class for the operation to use.

***However,***The real power lies in being able to configure an import lightning fast using the same syntax as you would to define your list views.

Table of Contents
-----------------

[](#table-of-contents)

1. [Installation](#installation)
2. [Usage](#usage)
3. [Column Types](#column-types)
    1. [Text](#text)
    2. [Number](#number)
    3. [Boolean](#boolean)
    4. [Date](#date)
    5. [Array](#array)
4. [Primary Keys](#primary-keys)
5. [Imports Without Primary Keys](#imports-without-primary-keys)
6. [Validation](#validation)
7. [Adding an Example File](#adding-an-example-file)
8. [Adding Your Own Columns](#adding-your-own-columns)
9. [Custom Import Classes](#custom-import-classes)
10. [Disabling User Mapping](#disabling-user-mapping)
11. [Delete Spreadsheet on Completion](#delete-spreadsheet-on-completion)
12. [Queued Imports](#queued-imports)
13. [Configuration](#configuration)
    1. [File Uploads](#file-uploads)
    2. [Queues](#queues)
    3. [Changing the Import log Model](#import-log)
    4. [Customising Translations](#translations)
    5. [Customising Views](#views)
14. [Events](#events)
15. [Restricting Access](#restricting-access)
16. [Credits](#credits)
17. [License](#license)

Installation
------------

[](#installation)

**Environment Requirements**

- PHP extension php\_zip
- PHP extension php\_xml
- PHP extension php\_gd2
- PHP extension php\_iconv
- PHP extension php\_simplexml
- PHP extension php\_xmlreader
- PHP extension php\_zlib

**Step 1.**

Require the package with composer:

```
composer require redsquirrelstudio/laravel-backpack-import-operation
```

This will also install [`maatwebsite/excel`](https://laravel-excel.com) if it's not already in your project.

**Step 2. (Optional)**

The service provider at: `RedSquirrelStudio\LaravelBackpackImportOperation\Providers\ImportOperationProvider`will be auto-discovered and registered by default. Although, if you're like me, you can add it to your `config/app.php`.

```
    'providers' => ServiceProvider::defaultProviders()->merge([
        /*
         * Package Service Providers...
         */
        //Some other package's service providers...
        RedSquirrelStudio\LaravelBackpackImportOperation\Providers\ImportOperationProvider::class,
    ])->toArray(),
```

**Step 3.**

Publish the config file:

```
php artisan vendor:publish --tag=laravel-backpack-import-operation-config
```

This will create a new file at `config/backpack/operations/import.php` allowing you to customise things such as the disk and path uploaded files should be stored at.

**Step 4.**

Publish and run the migration:

```
php artisan vendor:publish --tag=laravel-backpack-import-operation-migrations
```

*Then*

```
php artisan migrate
```

Usage
-----

[](#usage)

In your CRUD Controller where you need the import operation.

*Wait for it...*

**Add the import operation:**

```
class ExampleCrudController extends CrudController
{
    use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
    use \RedSquirrelStudio\LaravelBackpackImportOperation\ImportOperation;
    //...
```

But wait! There's more!

### Configuring the Import

[](#configuring-the-import)

Configuring a CRUD import is very similar to configuring the list or show view, here's an example:

```
    //Probably some more CRUD config...

    protected function setupImportOperation()
    {
        CRUD::addColumn([
           'name' => 'id',
           'label' => 'ID',
           'type' => 'number',
        ]);

        CRUD::addColumn([
           'name' => 'name',
           'label' => 'Name',
           'type' => 'text',
        ]);
    }

    //Fetch functions or something...
```

Within the `setupImportOperation()` function you can add CRUD columns with, in most cases, a name, label, and type. Each column corresponds to a model field.

The type of column is important as it specifies how the data from the spreadsheet will be processed before it is saved against the model.

### =========IMPORTANT==========

[](#important)

The columns you specify here correspond to the model fields **NOT**the spreadsheet columns. The user has the option to assign any spreadsheet column to any import column within the interface.

### =============================

[](#)

Column Types
------------

[](#column-types)

### Text

[](#text)

The simplest type of column, just takes the text from the spreadsheet and saves it to the model field.

**Example**

```
CRUD::addColumn([
   'name' => 'name',
   'label' => 'Name',
   'type' => 'text',
]);
```

### Number

[](#number)

This column will check whether the number is numeric, if it is, it will be saved against the model otherwise `null`will be used. (This field also supports decimal values).

**Example**

```
CRUD::addColumn([
   'name' => 'age',
   'label' => 'Age',
   'type' => 'number',
]);
```

### Boolean

[](#boolean)

By default, this column will evaluate whether the column contains: 'true', '1', or 'y' (case-insensitive). But you can specify what should be counted as true or false using the `'options'` key.

**Example**

```
CRUD::addColumn([
   'name' => 'active',
   'label' => 'Active Customer',
   'type' => 'boolean',
   'options' => [
        false => 'No',
        true => 'Yes',
    ]
]);
```

### Date

[](#date)

This column will take the input and try to convert it to a datetime, if successful, the datetime will be return as a [`Carbon\Carbon` ](https://carbon.nesbot.com/docs)instance, otherwise it will return null.

**Example**

```
CRUD::addColumn([
   'name' => 'date_of_birth',
   'label' => 'Birthday',
   'type' => 'date',
]);
```

### Array

[](#array)

This column is ideal for only importing one or more of a number of options. **Example**

```
CRUD::addColumn([
   'name' => 'type',
   'label' => 'Customer Type',
   'type' => 'array',
   'options' => [
        'retail' => 'Retail',
        'trade' => 'Trade',
        'other' => 'Other',
    ]
]);
```

In this example, the import will only save data from the column if it is 'Retail', 'Trade', or 'Other'. In these instances, values 'retail', 'trade', and 'other' will be saved respectively.

**Multiple Values**

The array column also supports multiple values.

**Example**

```
CRUD::addColumn([
   'name' => 'type',
   'label' => 'Customer Type',
   'type' => 'array',
   'multiple' => true,
   'options' => [
        'retail' => 'Retail',
        'trade' => 'Trade',
        'other' => 'Other',
    ]
]);
```

In this example, the user could import the following data:

```
Retail,Trade,Other

```

and the column would save the following array against the model's type field:

```
[
    'retail',
    'trade',
    'other'
]
```

For this to work, make sure to cast the model's field as an array within the `$casts` array, as shown below:

```
  protected $casts = [
        'types' => 'array',
  ];
```

In the case where you would like the user to be able to specify a comma seperated list of any values. You can add the following to the CRUD column config.

```
CRUD::addColumn([
   'name' => 'type',
   'label' => 'Customer Type',
   'type' => 'array',
   'multiple' => true,
   'options' => 'any'
]);
```

With this configuration, the user could put whatever they like. For example, if they imported dog,cat,rat - It would be saved to the model as:

```
[
    'dog',
    'cat',
    'rat'
]
```

`'options' => 'any'`

cannot be used without

`'multiple' => true `

as it does not make sense for this column type. In this case, just use a text column.

Primary Keys
------------

[](#primary-keys)

The import operation needs to know your model's primary key so that it knows whether to create or update with the row's data. By default, the operation will try to find a column you have added that has the model's primary key as the name.

For example, if your model's primary key is id, the operation would use this column as the primary key:

```
CRUD::addColumn([
   'name' => 'id',
   'type' => 'number',
]);
```

You'll be able to see on the mapping screen which column has been identified as the primary key.

If your primary key cannot be found, the operation instead will look for the first text or number column you have added.

You can also set a column as the primary key by adding the following config to the column:

```
CRUD::addColumn([
   'name' => 'id',
   'type' => 'number',
   'primary_key' => true,
]);
```

Imports Without Primary Keys
----------------------------

[](#imports-without-primary-keys)

You can disable the requirement for a primary key, however, it will mean that your import can only create new models and won't be able to update existing data. This can be useful in cases where you don't have a defined primary key and are relying on the model's auto-incrementing ID. This setting can also help where you want to be able to specify a unique column that the user shouldn't be able to create multiples of or change existing data for.

TLDR: Imports with this setting enabled cannot update existing data, only import new data.

Add the following line to your `setupImportOperation` function:

```
    protected function setupImportOperation()
    {
        $this->withoutPrimaryKey();
        //Some column config...
```

Validation
----------

[](#validation)

Validating your imports works similarly to how you would validate a create or update method, call the following function within the `setupImportOperation`function:

```
    protected function setupImportOperation()
    {
        CRUD::setValidation(CustomerRequest::class);
        //Some column config...
```

The form request should validate what is required for your model, **Not** the spreadsheet columns, again because the column headers shouldn't matter as the user can map them.

Adding an Example File
----------------------

[](#adding-an-example-file)

You can also add a link for your user to download an example spreadsheet with data that you would expect them to upload. To set this use the following function within the `setupImportOperation`function:

```
    protected function setupImportOperation()
    {
        $this->setExampleFileUrl('https://example.com/link-to-your-download/file.csv');
        //Some column config...
```

Doing this will provide them with a link like this when uploading their file:

[![Screenshot of the operation's example download](https://raw.githubusercontent.com/redsquirrelstudio/laravel-backpack-import-operation/dev/assets/example-download.jpg?raw=true)](https://raw.githubusercontent.com/redsquirrelstudio/laravel-backpack-import-operation/dev/assets/example-download.jpg?raw=true)

Adding Your Own Columns
-----------------------

[](#adding-your-own-columns)

The import operation offers the option to create your own handlers. This only takes two steps.

**Step 1.**

I've included an artisan command to generate a custom column skeleton:

```
php artisan backpack:import-column ExampleColumn
```

This will generate a blank import column for you at `app\Imports\Columns`.

```
