Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kgp43's avatar
Level 2

Add new users to external accounting software, using API

Hi,

I need to add new users to an external website, using their REST api. Do i just add my code to the registerController, or is there a smarter way to handle this?

This add the user to the external website, but I got a feeling there are a much much smarter and cleaner solution to do it.

Also, economic_customerNumber is not added to my laravel users table. I can't even add a number manually. No errors or anything, just missing the data in the table/row.

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/cp';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        # Add user to external website
        
            # create a new cURL resource
            $ch = curl_init();
            
            $ch_data = array(
                'name' => $data['name'],
                'address' => '',
                'email' => $data['email'],
                'zip' => '',
                'city' => '',
                'country' => 'Danmark',
                'corporateIdentificationNumber' => '',
                'customerGroup' => array(
                    'customerGroupNumber' => 1
                ),
                'currency' => 'DKK',
                'paymentTerms' => array(
                    'paymentTermsNumber' => 1
                ),
                'vatZone' => array(
                    'vatZoneNumber' => 1
                )
            );
            
            $options = array(
                CURLOPT_URL => 'https://restapi.e-conomic.com/customers',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_HTTPHEADER => array(
                    'X-AppSecretToken:...',
                    'X-AgreementGrantToken:...',
                    'Content-Type:application/json; charset=utf-8'
                ),
                CURLOPT_POSTFIELDS => json_encode($ch_data)
            );
            
            curl_setopt_array($ch, $options);
            
            # grab response
            $res = curl_exec($ch);
            $json = json_decode($res);
            
            $curl_info = curl_getinfo($ch);
            
            # close resource
            curl_close($ch);
        
        # Add user to Laravel database
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'economic_customerNumber' => $json->customerNumber,
            'password' => bcrypt($data['password']),
        ]);
        
    }
}
0 likes
5 replies
mikefolsom's avatar

In my mind, this is a perfect use case for Laravel's queue system. My approach would be to validate input and create the user in this controller, then dispatch a job (something like CreateEconomicCustomer, perhaps) to the queue—either directly from the controller, or via an event listener.

The job would then take over the responsibility of making the API call to create the remote record and updating the user record with the economic_customerNumber. I suspect that field is not currently in your $fillable array, so it is not being mass-assigned. For example:

<?php

namespace App\Jobs;

use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class CreateEconomicCustomer implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    protected $data;

    public function __construct(User $user, $data)
    {
        $this->user = $user;
        $this->data = $data;
    }

    public function handle()
    {
        // Delegate actual API logic and update user...
        $this->user->sendToApi($this->data);
    }
}

I also suggest looking into using Guzzle instead of directly calling cURL. It will give you much better control of your HTTP requests.

Finally, if you are on a server where running a queue worker is too difficult, you could always trigger artisan commands via cron/Laravel scheduled tasks. For example, find all user records where the economic user field is null, then run the API call on each one of those, updating the user record in the process.

kgp43's avatar
Level 2

Thanks for your reply.

I have already added the field to $fillable and getting the data info the table etc.

Going to look into Queues as you suggested, and separating the code. Thanks for that :)

I got one question though. How do you validate the input? I know how to validate form inputs, but not sure about a string.

mikefolsom's avatar

The input is validated just as you are currently doing it.

kgp43's avatar
Level 2

Hmm... I don't think I validate the return message from the RestAPI. I just put it straight into the database, right?

Yes, the column in the database is added to $fillable, but thats all I did. I have not defined what the string is allowed to contain.

Maybe i'm wrong.

mikefolsom's avatar

If it's a trusted source, you're probably safe to update that column in your database. If you want to be extra cautious you could (for example) match against a regex before using the value.

Please or to participate in this conversation.