Laravel 5.1 Background Task that Queries Database Fails to Work when hooked to an Azure Web Job

I am having a strange problem using WebJobs on Azure to run Laravel Background tasks.

I have this code in my Laravel ExpireContactsFromDatabase command's handle() method

public function handle()
{

* Update contacts that are old and past their expiry date but that have not been deleted
* Set their deleted at to the current timestamp
*/
$contact = Contact::where('expiry_date', '<=', date('Y-m-d H:i:s'))
->whereNull('deleted_at')
->update(array('deleted_at' => date('Y-m-d H:i:s')));
Log::info("200" . " " . "Contacts clearing executed successfully, see response from db :::: " . serialize($contact));

}

I have successfully registered this command in app\Console\Kernel.php, like so:

This is running very well on my local development machine. I configured a cron job on my laptop and it executes this command and expires the old contacts as expected.

The problem comes in when I migrate the application from localhost to Ms Azure. I configure a WebJob to run continuosly, give it the path to artisan and issue schedule run. I do this in using a .bat file, like so:

and I check my log files, I see the response from the database (logged into expired_contacts_results_dbresponse.txt) as follows:

[2016-10-20 12:21:43] local.ERROR: exception 'PDOException' with message 'SQLSTATE[HY000] [2002] An attempt was made to access a socket in a way forbidden by its access permissions.
' in D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:55

My guess is that the way laravel is connecting to the database has issues in this case. However, other components of my application use the same connection codes and they are working well so In am confused. Scouring the internet for an exact solution to this problem has not worked.

I am running my app on Azure on the D1 Shared Hosting Plan and using the convenient Azure MySQLInApp database for my database storage.

It seems the internal PHP runtime in Web App doesn't have sufficient permission to access to MySQL in App. In my test, I even create a test script leveraging the test connection code at Get the database connection string, and execute PHP test.php in KUDU console site, I would get the same issue with you.

But it worked fine if I access it via HTTP request (Which will be handled via IIS). So please try the following workaround. Implementing your functionality and expose as a Restful API. In Webjob script, you can generate a HTTP request to call this API.