Create users from CSV File with File.create:after hook

Hi again!

I am trying to create users from a spreadsheet uploaded in the backend.

So I try to achieve this by using the File.create:after hook and the csv-function as described here.

Unfornately, I get the error message “file(http://localhost:8080/media/pages/user-upload/162...011/test.csv): Failed to open stream: HTTP request failed!”

Is the csv file ready to be read by the csv function from within the hook? If not, does someone maybe have a better approach for my problem?

This is my code so far:

'hooks' => [
    'file.create:after' => function ($file) {
      if ($file->template() === 'userlist') {

        try {
          $csv = csv($file->url(), ';');
          $users = array_map(function ($user) {
            return [
              'email'     => $user['email'],
              'name'      => $user['name'],
              'role'      => 'customer',
              'language'  => $user['sprache'],
              'password'  => 'password'
            ];
          }, $csv);

          return Users::factory($users);
        } catch (Kirby\Exception\Exception $ex) {
          return $ex->toArray();
        }
      }
    }
  ],

Thank you very much in advance!

Okay, I figured out my first mistake. Instead of $file->url(), $file->root() is the way to go.

But still, no users are created. Does anyone see, where the reason for that could be?

That code doesn’t actually create users, you have to use $users->create().

You’re right. Thank you!

Hello,

I’m trying to achieve exactly the same bu since this post is more than 5 years ago I’m wondering if still working.

@sigi Could you let us know the exact code you used?

The post is from June this year, Kirby 3 is not even 5 years old :wink:

I guess he read the image as “June 2015” and not “15. June 2021” :slight_smile:

I used this:

'file.create:after' => function ($file) {
      if ($file->template() === 'userlist') {

        try {
          $kirby = kirby();
          $kirby->impersonate('kirby');

          $csv = csv($file->root(), ';');
          $users = array_map(function ($user) {
            $password = Str::random(12, 'alphaNum');
            kirby()->users()->create([
              'email'     => $user['user_email'],
              'name'      => $user['first_name'] . ' ' . $user['last_name'],
              'role'      => 'customer',
              'password'  => $password,
              'content'   => [
                'street'    => $user['address'],
                'city'      => $user['city'],
                'country'   => $user['country'],
                'zip'       => $user['zip']
              ]
            ]);
          }, $csv);
        } catch (Kirby\Exception\Exception $ex) {
          return $ex->toArray();
        }
      }
    },