WordPress: user roles changing in plugin and DB, but not in WP Backend

First of all, I’m new to programming so I could use a little help.
I have been given the task to make a custom JWT login plugin.
With that said, I have a small problem – one of them is that when I select roles in the plugin, they change only in the plugin and in the DB, but I want them to change in the WordPress Backend as well.

I am attaching a code snippet below, hopefully you will be able to help me further.

My PHP:

 public function checkUserRole($apps)
    {
        $thisApp = get_option('kt_jwt_login_client_id');
        $key = array_search($thisApp, array_column($apps, 'app'));
        if (in_array('admin', $apps[$key]->roles)) {
            return 'admin';
        } elseif (in_array('manager', $apps[$key]->roles)) {
            return 'manager';
        } else {
            return false;
        }
    }

    /**
     *
     * Create User in WordPress if not already there
     * @return int user ID
     * @throws Exception
     *
     */
    public function createUserIfnotExists($userInfo)
    {
        //get fields from admin settings
        $email = get_option('kt_jwt_login_email');
        $first_name = get_option('kt_jwt_login_first_name');
        $family_name = get_option('kt_jwt_login_last_name');
        $full_name = get_option('kt_jwt_login_first_name') . ' ' . get_option('kt_jwt_login_last_name');
        $company = get_option('kt_jwt_login_company');

        if ($this->checkUserRole($userInfo->applications) == 'admin') {
            $role = add_role('Administrator');
        } elseif ($this->checkUserRole($userInfo->applications) == 'manager') {
            $role = add_role('Contributor');
        } elseif (strpos(strtolower($userInfo->$company), strtolower(get_option('kt_jwt_login_employee'))) !== false) {
            $role = add_role('Author');
        } else {
            $role = add_role('Subscriber');
        }
        echo "Role: $rolen";
        var_dump($role);

        if (email_exists($userInfo->email)) {
            $user = get_user_by('email', $userInfo->email);
            $user_id = $user->ID;
            $user->remove_role($role);
            $user->add_role($role);

            //update user data
            $user_data = wp_update_user(array(
                'ID' => $user_id,
                'first_name' => $userInfo->first_name,
                'last_name' => $userInfo->last_name,
                'display_name' => $userInfo->first_name . ' ' . $userInfo->last_name,
                'role' => $role
            ));

            if (is_wp_error($user_data)) {
                echo '<h1>There was an error; possibly this user does not exists</h1>';
            } else {
                echo '<h1>Success! User profile updated.</h1>';
            }
            // end of update user data
        } else {
            $user_id = wp_insert_user(array(
                'user_login' => $userInfo->email,
                'user_pass' => random_bytes(24),
                'user_email' => $userInfo->email,
                'first_name' => $userInfo->first_name,
                'last_name' => $userInfo->last_name,
                'display_name' => $userInfo->full_name,
                'role' => $role
            ));
        }

        // Set or update woocommerce userinfo:
        $this->updateWoocommerceMetaData($user_id, $userInfo);

        // Set user role using taxonomy 'role':
        $user = new WP_User($user_id);
        $user->set_role($role);

        return $user_id;

    }

My frontend:

<div class="wrap">
    <h1>Settings</h1>
    <br>
    <div class="container">
        <div class="col-sm-12">
            <div class="panel panel-primary">
                <div class="panel-body">
                    <form class="form-horizontal" action="options.php" method="post" style="margin-left: 40px;">
                        <h4>Connection Settings</h4>

                        <div class="card" style="max-width: 650px">
                            <?php
                            settings_fields('admin_section');
                            do_settings_sections('plugin-options');
                            ?>
                            <button type="submit"
                                    class="btn btn-outline-success"
                                    style="width: 20%; align-self: center; margin-top: 20px">
                                Save
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<?php
... 

function display_role_form_element()
{
    $roles = wp_roles();
    ?>
    <select name="kt_jwt_login_role" id="kt_jwt_login_role" style="padding: 0 176px 0 8px">
        <?php

        foreach ($roles->roles as $role => $roleObj) {
            echo '<option value="' . $role . '" ';
            if ($role == get_option('kt_jwt_login_role')) echo ' selected ';
            echo '>' . $roleObj['name'] . '</option>';
        }
        ?>
    </select>
    <?php
}

function display_userProfileUrl_form_element()

Symfony access denied exception on dev environment

My symfony project throws cache write access denied errors seemingly randomly, only in development and testing modes, and when I send multiple requests in a row. Although it doesn’t happen in production, it’s really annoying in development.

I already checked this link, put umask(0000) in the beginning of my bin/console and public/index.php files, and still the same problem.

Here’s a example of a regular output that I get from the project.

Acces is denied exception

I’m using apache over Wamp64, regular installation. Does anyone have this same problem? Is there a cure for this permissions disease?

Laravel Livewire multispep form

this is my blade file
i have 2 problem i want different variable from javascript in this 3 step and in final page i want make a summary of 3 different preset and save to my database like: id_client: = 1 ; order_1d =1 sub_order = 1

id_client: = 1 ; order_1d =1 sub_order = 2

id_client: = 1 ; order_1d =1 sub_order = 3

I want save in my database the information corretct



    


{{--    has('ordini.id_tipo') ? 'invalid' : '' }}">
        {{ trans('cruds.ordini.fields.id_tipo') }}
        
        
            {{ $errors->first('ordini.id_tipo') }}
        
        
            {{ trans('cruds.ordini.fields.id_tipo_helper') }}
        
    --}}

    
        
            {{ trans('global.save') }}
        
        
            {{ trans('global.cancel') }}
        
    

{{----}}






{{--Inizio sessione  vecchia, scelta cliente--}}












    

        {{-- STEP 1 --}}

        @if ($currentStep == 1)


            
                

                    Farmaci della mattina
                    
                        
                            
                                has('ordini.cliente_id') ? 'invalid' : '' }}">
                                    {{ trans('cruds.ordini.fields.cliente') }}
                                    listsForFields['cliente']" wire:model="ordini.cliente_id" />
                                    
                                        {{ $errors->first('ordini.cliente_id') }}
                                    
                                    
                                        {{ trans('cruds.ordini.fields.cliente_helper') }}
                                    
                                
                            
                            
                                has('prodotti') ? 'invalid' : '' }}">
                                    {{ trans('cruds.ordini.fields.prodotti') }}
                                    listsForFields['prodotti']" multiple />
                                    
                                        {{ $errors->first('prodotti') }}
                                    
                                    
                                        {{ trans('cruds.ordini.fields.prodotti_helper') }}
                                    
                                
                            
                        

                        
                            Description
                            
                            @error('description'){{ $message }}@enderror
                        
                    
                
            
        @endif

        {{-- STEP 2 --}}

        @if ($currentStep == 2)


            
                
                    Farmaci della pranzo
                    

                        
                            
                                has('ordini.cliente_id') ? 'invalid' : '' }}">
                                    {{ trans('cruds.ordini.fields.cliente') }}
                                    listsForFields['cliente']" wire:model="ordini.cliente_id" />
                                    
                                        {{ $errors->first('ordini.cliente_id') }}
                                    
                                    
                                        {{ trans('cruds.ordini.fields.cliente_helper') }}
                                    
                                
                            
                            
                                has('prodotti') ? 'invalid' : '' }}">
                                    {{ trans('cruds.ordini.fields.prodotti') }}
                                    listsForFields['prodotti']" multiple />
                                    
                                        {{ $errors->first('prodotti') }}
                                    
                                    
                                        {{ trans('cruds.ordini.fields.prodotti_helper') }}
                                    
                                
                            
                        


                    
                
            

        @endif
        {{-- STEP 3 --}}

        @if ($currentStep == 3)


            
                
                    Farmaci della sera
                    
                        
                            
                                has('ordini.cliente_id') ? 'invalid' : '' }}">
                                    {{ trans('cruds.ordini.fields.cliente') }}
                                    listsForFields['cliente']" wire:model="ordini.cliente_id" />
                                    
                                        {{ $errors->first('ordini.cliente_id') }}
                                    
                                    
                                        {{ trans('cruds.ordini.fields.cliente_helper') }}
                                    
                                
                            
                            
                                has('prodotti') ? 'invalid' : '' }}">
                                    {{ trans('cruds.ordini.fields.prodotti') }}
                                    listsForFields['prodotti']" multiple />
                                    
                                        {{ $errors->first('prodotti') }}
                                    
                                    
                                        {{ trans('cruds.ordini.fields.prodotti_helper') }}
                                    
                                
                            
                        
                    
                
            
        @endif

        {{-- STEP 4 --}}
        @if ($currentStep == 4)


            
                
                    STEP 4/4 - Attachments
                    
                        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Itaque delectus officia inventore id facere at aspernatur ad corrupti asperiores placeat, fugiat tempora soluta optio recusandae eligendi impedit ipsam ullam amet!
                        
                            CV
                            
                            @error('cv'){{ $message }}@enderror
                        
                        
                            
                                 You must agree with our Terms and Conditions
                            
                            @error('terms'){{ $message }}@enderror
                        
                    
                
            

        @endif

        

            @if ($currentStep == 1)
                
            @endif

            @if ($currentStep == 2 || $currentStep == 3 || $currentStep == 4)
                Back
            @endif

            @if ($currentStep == 1 || $currentStep == 2 || $currentStep == 3)
                Next
            @endif

            @if ($currentStep == 4)
                Submit
            @endif


        

    




my controller:

<?php

namespace AppHttpLivewireOrdini;

use AppModelsCustomer;
use AppModelsOrdini;
use AppModelsProduct;
use LivewireComponent;

class Create extends Component
{
    public Ordini $ordini;

    public array $prodotti = [];

    public array $listsForFields = [];


    public $totalSteps = 4;
    public $currentStep = 1;







    public function mount(Ordini $ordini)
    {
        $this->ordini = $ordini;
        $this->initListsForFields();
    }

    public function render()
    {
        return view('livewire.ordini.create');
    }

    public function submit()
    {
        $this->validate();

        $this->ordini->save();
        $this->ordini->prodotti()->sync($this->prodotti);

        return redirect()->route('admin.ordinis.index');


    }


    public function increaseStep(){
        $this->resetErrorBag();
        $this->validate();
        $this->currentStep++;
        if($this->currentStep > $this->totalSteps){
            $this->currentStep = $this->totalSteps;
        }
    }

    public function decreaseStep(){
        $this->resetErrorBag();
        $this->currentStep--;
        if($this->currentStep < 1){
            $this->currentStep = 1;
            //render();
        }
    }


    protected function rules(): array
    {
        return [
            'ordini.name' => [
                'string',
                'nullable',
            ],
            'ordini.cliente_id' => [
                'integer',
                'exists:customers,id',
                'nullable',
            ],
            'prodotti' => [
                'array',
            ],
            'prodotti.*.id' => [
                'integer',
                'exists:products,id',
            ],
            'ordini.id_tipo' => [
                'integer',
                'min:-2147483648',
                'max:2147483647',
                'nullable',
            ],
        ];
    }

    protected function initListsForFields(): void
    {
        $this->listsForFields['cliente']  = Customer::pluck('name', 'id')->toArray();
        $this->listsForFields['prodotti'] = Product::pluck('name', 'id')->toArray();
    }
}
and my other blade select list

<pre>
 <div>
    <div wire:ignore class="w-full">
        @if(isset($attributes['multiple']))
            <div id="{{ $attributes['id'] }}-btn-container" class="mb-3">
                <button type="button" class="btn btn-info btn-sm select-all-button">{{ trans('global.select_all') }}</button>
                <button type="button" class="btn btn-info btn-sm deselect-all-button">{{ trans('global.deselect_all') }}</button>
            </div>
        @endif
        <select class="select2 form-control" data-placeholder="{{ __('Select your option') }}" {{ $attributes }}>
            @if(!isset($attributes['multiple']))
                <option></option>
            @endif
            @foreach($options as $key => $value)
                <option value="{{ $key }}">{{ $value }}</option>
            @endforeach
        </select>
    </div>
</div>

@push('scripts')
    <script>
        document.addEventListener("livewire:load", () => {
    let el = $('#{{ $attributes['id'] }}')
    let buttonsId = '#{{ $attributes['id'] }}-btn-container'

    function initButtons() {
        $(buttonsId + ' .select-all-button').click(function (e) {
            el.val(_.map(el.find('option'), opt => $(opt).attr('value')))
            el.trigger('change')
        })

        $(buttonsId + ' .deselect-all-button').click(function (e) {
            el.val([])
            el.trigger('change')
        })
    }

    function initSelect () {
        initButtons()
        el.select2({
            placeholder: '{{ __('Select your option') }}',
            allowClear: !el.attr('required')
        })
    }

    initSelect()

    Livewire.hook('message.processed', (message, component) => {
        initSelect()
    });

    el.on('change', function (e) {
        let data = $(this).select2("val")
        if (data === "") {
            data = null
        }
@this.set('{{ $attributes['wire:model'] }}', data)
    });
});
    </script>
@endpush  
</pre>


i have 2 problem i want different variable from javascript in this 3 step and in final page i want make a summary of 3 different preset and save to my database like: id_client: = 1 ; order_1d =1 sub_order = 1

id_client: = 1 ; order_1d =1 sub_order = 2

id_client: = 1 ; order_1d =1 sub_order = 3

I want save in my database the information corretct
    

Oauth 2 token error in Laravel due to BigQuery Integration

So i have this code which i want to request for the table from google cloud BigQuery in Laravel 8 and i have already create a service account in my Google CLoud as well as made a key and got the json file with all the details of the Bigquery. When i call the query it doesnt go through and ask me for the permission error as follows

{ "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Invalid Credentials", "domain": "global", "reason": "authError", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "ACCESS_TOKEN_EXPIRED", "domain": "googleapis.com", "metadata": { "method": "google.cloud.bigquery.v2.JobService.InsertJob", "service": "bigquery.googleapis.com" } } ] } }

This is my controller

 error_log('hello');
         $bigQuery = new BigQueryClient([

             'keyFile' => json_decode(file_get_contents(base_path() . env('GOOGLE_APPLICATION_CREDENTIALS', "env path not set")), true)
         ]);
        //  $date = str_replace("-", "", $req->date);
         // Run a query and inspect the results.
         $queryJobConfig = $bigQuery->query(
             'SELECT event.value.string_value as Screen, count(*) as ViewCount,
             FROM `rtiapp-4593f.analytics_353940796.*`,
                 UNNEST(event_params) as event
             WHERE event.key = "firebase_screen"
             GROUP BY event.value.string_value
             ORDER BY ViewCount DESC LIMIT 20'
         );
         error_log('hi');
         $queryResults = $bigQuery->runQuery($queryJobConfig);
         error_log('hi');
         error_log('queryResults');
         error_log( $queryResults);
         $info = $queryResults->info();
         $results = $info['rows'];
         error_log($results);
         $schema = $info['schema'];
         $fields =  $schema['fields'];
         error_log($info);

May i know where i am going wrong please. Any help would be appreicated.

I tried many things including making a new service account and put that json there and aslo using gcloud login but still no luck.

Disable dates + weekday numbers with flatpickr

I would like to be able to deactivate days + weekday numbers 1 to 7.

calendar.flatpickr({
                        disable: dateUnvailableCalendar,
                        minDate: "today",
                        onChange: function (selectedDates, dateStr) {
                            calendarHandleChange(dateStr);
                        }
                    });

This is what I have already done. this disable days i send in an array.
now i wish i could disable day number 5 and 7 of every week of the whole year.
Do you know how I can do this please?

Thank you for help.

How to get the minute difference between two Carbon objects ignoring the date?

I have a start date

$start = Carbon::parse('2023-03-01 10:00:00');

and an end date

$end = Carbon::parse('2023-03-02 17:00:00');

I want to get the minutes between 10:00:00 and 17:00:00 ignoring the date.

I made this working with

$time_end = $end->toTimeString();
$time_start = $start->toTimeString();
$duration = Carbon::parse($time_end)->diffInMinutes(Carbon::parse($time_start));

but with the toTimeString() I kind of leaving the Carbon object and I feel there must be a better approach.

Even if I don’t find a function like that in the CarbonInterface I still feel this must be accomplished better.

Another idea I had is:

$duration = $end->diffInMinutes($start) - 24 * 60  * $end->diffInDays($start);

Symfony collection don’t save array but class name

I’ve got symfony form with CollectionType. It’s a multistep form and when im dumping data after each step it saves properly:

AppEntityRezylientnaArchitektura {#654 ▼
  -id: null
  -BezpInf: DoctrineCommonCollectionsArrayCollection {#655 ▼
    -elements: array:1 [▼
      0 => array:3 [▼
        "BezpInf_1" => "0"
        "BezpInf_2" => "1"
        "BezpInf_3" => "1"
      ]
    ]
  }
  -useruuid: "ea9ae76e-b688-11ed-be51-494b48375171"

Form:

$builder->add('useruuid', HiddenType::class, [
                    'data' => $this->getUserUUID(),
                ]);

                $builder->add('BezpInf', CollectionType::class, [
                    'entry_type' => AnswersTempType::class,
                    'allow_extra_fields' => true,
                    'entry_options' => [
                        'label' => false,                   
                    ],
                    'label' => false,
                    // 'by_reference' => false, 
                ]);

Entity:

#[ORMEntity(repositoryClass: RezylientnaArchitekturaRepository::class)]
class RezylientnaArchitektura
{
    #[ORMId]
    #[ORMGeneratedValue]
    #[ORMColumn]
    private ?int $id = null;

    #[ORMColumn(length: 255)]
    private $BezpInf = null;

    #[ORMColumn(length: 255)]
    private ?string $useruuid = null;

    public function __construct()
    {
        $this->BezpInf = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getBezpInf(): Collection
    {
        return $this->BezpInf;
    }

    public function setBezpInf(string $BezpInf): self
    {
        $this->BezpInf = $BezpInf;

        return $this;
    }

    public function getUseruuid(): ?string
    {
        return $this->useruuid;
    }

    public function setUseruuid(string $useruuid): self
    {
        $this->useruuid = $useruuid;

        return $this;
    }
}

And now tricky part. When i want to save it into db in classic way:

// ...

$em = $this->doctrine->getManager();
$em->persist($answer);
$em->flush();

// ...

it saves like:

id bezpinf useruuid
….. DoctrineCommonCollectionsArrayCollection@000000000000032f0000000000000000 …..

When i add to a form

'by_reference' => false

it render in a dump – DoctrineCommonCollectionsArrayCollection@000000000000032f0000000000000000 and save the same.

How can i persist my arraycollection into db properly?

php calculating total cases from 2 different inputs

so, this seems really simple, but I have been scratching my head for about an hour now.
Simple math, but I cannot replicate with code.
1 case = 4 bags, 4 bags = 8 bottles, 8 bottles = 1 case.

<form method="post">
    <input type="text" name="cases" placeholder="cases...">
    <input type="text" name="bottles" placeholder="bottles...">
    <button name="submit">submit</button>
    <?php echo $output; ?>
</form>

if(isset($_POST['submit'])){
    $cases = $_POST['cases'];
    $bottles = $_POST['bottles'];
    $xcases = $cases * 4;
    $xbottles = $bottles / 4;
    $c = $xbottles + $xcases;
    $output = $xbottles;
}

I’ve tried changing the math around, but just can’t seem to get it right.

Calling Sub Class Method On Parent PHP Class

I have 2 PHP class that related each other, rather than using __construct, I tryin to using extends to combine these 2 class. But why sub class method cant called from parent class? There’s no either result or error displayed but warning about reach memory limit.

here my example code:

<?php
 class Me {

    public $you;    

  public function __construct() {
     $this->you = new You;
  }

public  function Hi()
    {
        return 'Hi You';
    }

public  function WhatYouSaid()
    {
        return $this->you->Me();
    }   
    
}

class You extends Me{

public  function Me()
        {
            return 'Yes Me';
        }
}

$talk = new You;
print_r($talk->WhatYouSaid());

https://onlinephp.io/c/3d84d

I received error:
Fatal error: Allowed memory size of xxx bytes exhausted (tried to allocate xx bytes)

Composer install squizlabs/php_codesniffer PHP 7.4 on Windows 10 is failed to install

I have the following error installing squizlabs/php_codesniffer with Composer v. 1.10.20 on Windows 10 with PHP 7.4.4:


[ComposerExceptionNoSslException]
  The openssl extension is required for SSL/TLS protection but is not available. If you can not enable the openssl ex
  tension, you can disable this error, at your own risk, by setting the 'disable-tls' option to true.

How can I fix it? How can I install openssl extension on Windows 10?

I have tried to install squizlabs/php_codesniffer=* composer library using command: composer.bat global require "squizlabs/php_codesniffer=*" and it is failed with error posted above.
I’m expecting to fix the error by installing and enabling missing libraries or packages.

ExceptionWrapper with PHPUnit on Laravel 9

I want to upgrade my project on Laravel 8 to 9 (And then 10, but I do it step by step)
I tested on Laravel Sail the updating, I have no dependencies errors but I can’t execute my PHPUnit tests to be sure my application is still working…

All Unit tests is still working but I have a “PHPUnitFrameworkExceptionWrapper” on all my Features tests that says “Illegal offset type in isset or empty” catched on vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:216

Here my requires in composer.json :

"require": {
    "php": "^7.3|^8.1",
    "barryvdh/laravel-cors": "^3.0",
    "fanmade/laravel-bitwise-trait": "^2.0",
    "fruitcake/laravel-cors": "^2.0",
    "guzzlehttp/guzzle": "^7.0.1",
    "laravel-notification-channels/apn": "^5.0",
    "laravel/framework": "^9.0",
    "laravel/sanctum": "^2.11",
    "laravel/tinker": "^2.5",
    "laravel/ui": "^3.4",
    "ozdemirburak/iris": "^2.4"
},
"require-dev": {
    "fakerphp/faker": "^1.9.1",
    "laravel/sail": "^1.0.1",
    "laravel/telescope": "^4.6",
    "mockery/mockery": "^1.4.4",
    "nunomaduro/collision": "^6.1",
    "phpunit/phpunit": "^9.5",
    "spatie/laravel-ignition": "^1.0"
},

And my PHPUnit.xml :

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
     bootstrap="vendor/autoload.php"
     colors="true"
>
<testsuites>
    <testsuite name="Unit">
        <directory suffix="Test.php">./tests/Unit</directory>
    </testsuite>
    <testsuite name="Feature">
        <directory suffix="Test.php">./tests/Feature</directory>
    </testsuite>
</testsuites>
<coverage processUncoveredFiles="true">
    <include>
        <directory suffix=".php">./app</directory>
    </include>
</coverage>
<php>
    <server name="APP_ENV" value="testing"/>
    <server name="BCRYPT_ROUNDS" value="4"/>
    <server name="CACHE_DRIVER" value="array"/>
    <server name="DB_CONNECTION" value="sqlite"/>
    <server name="DB_DATABASE" value=":memory:"/>
    <server name="MAIL_MAILER" value="array"/>
    <server name="QUEUE_CONNECTION" value="sync"/>
    <server name="SESSION_DRIVER" value="array"/>
    <server name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>

Any ideas ?
Thanks you !

HttpClient PostAsync error: The request was aborted: The connection was closed unexpectedly

I have a VB.net application that I need to connect to an API Controller coded in PHP with Laravel as the framework. I am getting the below error when the code hits PostAsync.

System.AggregateException was caught
  HResult=-2146233088
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
       at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
       at System.Threading.Tasks.Task`1.get_Result()
       at .Common.Web._Closure$__1._Lambda$__1() in C:Users...Web.vb:line 82
  InnerException: System.Net.Http.HttpRequestException
       HResult=-2146233088
       Message=An error occurred while sending the request.
       InnerException: System.Net.WebException
            HResult=-2146233079
            Message=The request was aborted: The connection was closed unexpectedly.
            Source=System
            StackTrace:
                 at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
                 at System.Net.ConnectStream.ReadWithoutValidation(Byte[] buffer, Int32 offset, Int32 size, Boolean abortOnError)

This is the code:

Private Shared Function MakeRequest(ByVal RequestedUrl As String, ByVal Params As Dictionary(Of String, String)) As Task(Of WebResponse)

            Return Threading.Tasks.Task(Of WebResponse).Factory.StartNew(
                Function()
                    Dim httpResponse As HttpResponseMessage = Nothing
                    Try
                        Using httpClient As HttpClient = New HttpClient()

                            Dim tmp As String = _httpMethod
                            If Not _apiUrl.EndsWith("/") Then
                                tmp = _httpMethod + "://"
                            End If

                            System.Net.ServicePointManager.SecurityProtocol = DirectCast(3072, System.Net.SecurityProtocolType)
                            Dim responseStatus As Threading.Tasks.Task(Of HttpResponseMessage) = httpClient.PostAsync(tmp & _apiUrl, New FormUrlEncodedContent(Params))
                            httpResponse = responseStatus.Result
                            httpResponse.EnsureSuccessStatusCode()

                            Dim responseContent As Threading.Tasks.Task(Of String) = httpResponse.Content.ReadAsStringAsync()
                            Dim responseBody As String = responseContent.Result

                            Dim webResponse As WebResponse = JsonConvert.DeserializeObject(Of WebResponse)(responseBody)
                            Return webResponse

                        End Using
                    Catch ex As Exception
                        If httpResponse IsNot Nothing Then
                            Return New WebResponse(CInt(httpResponse.StatusCode).ToString(), "Error " + CInt(httpResponse.StatusCode).ToString() + ": " + ex.Message, Nothing)
                        Else
                            Return New WebResponse("500", ex.Message, Nothing)
                        End If
                    End Try
                End Function)

        End Function

I have tried everything I could find on google with the same error but nothing seems to work. I am using XAMPP v3.2.2 with Apache 2.4.37.0 and OpenSSL 1.1.1a.

The server doesn’t seem to allow the client (VB.net app, using TLS 1.2) to connect and I am puzzled why. The Apache access logs don’t help either. Note that I can connect to the API via Postman and it does the POST request successfully.

I really hope someone can shed some light on this as I am stuck here for days.

Laravel eloquent multi relationship with multiple query

this is my Order MOdel

    public function cliente()
    {
        return $this->belongsTo(Customer::class);
    }

    public function product()
    {
        return $this->belongsToMany(Product::class);
    }

and my Order Controller

<?php

namespace AppHttpLivewireOrder;

use AppModelsCustomer;
use AppModelsOrder;
use AppModelsProduct;
use LivewireComponent;

class Create extends Component
{
    public Order $order;

    public array $product = [];

    public array $listsForFields = [];

    public function mount(Order $order)
    {
        $this->order = $order;
        $this->initListsForFields();
    }

    public function render()
    {
        return view('livewire.order.create');
    }

    public function submit()
    {
        $this->validate();

        $this->order->save();
        $this->order->product()->sync($this->product);

        return redirect()->route('admin.orders.index');
    }

    protected function rules(): array
    {
        return [
            'order.codice_fiscale' => [
                'string',
                'nullable',
            ],
            'order.cliente_id' => [
                'integer',
                'exists:customers,id',
                'nullable',
            ],
            'product' => [
                'array',
            ],
            'product.*.id' => [
                'integer',
                'exists:products,id',
            ],
            'order.nome' => [
                'string',
                'nullable',
            ],
        ];
    }

    protected function initListsForFields(): void
    {
        $this->listsForFields['cliente'] = Customer::pluck('descrizione', 'id')->toArray();
        $this->listsForFields['product'] = Product::pluck('name', 'id')->toArray();
    }
}

<div class="form-group {{ $errors->has('order.codice_fiscale') ? 'invalid' : '' }}">
    <label class="form-label" for="codice_fiscale">{{ trans('cruds.order.fields.codice_fiscale') }}</label>
    <input class="form-control" type="text" name="codice_fiscale" id="codice_fiscale" wire:model.defer="order.codice_fiscale">
    <div class="validation-message">
        {{ $errors->first('order.codice_fiscale') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.order.fields.codice_fiscale_helper') }}
    </div>
</div>
<div class="form-group {{ $errors->has('order.cliente_id') ? 'invalid' : '' }}">
    <label class="form-label" for="cliente">{{ trans('cruds.order.fields.cliente') }}</label>
    <x-select-list class="form-control" id="cliente" name="cliente" :options="$this->listsForFields['cliente']" wire:model="order.cliente_id" />
    <div class="validation-message">
        {{ $errors->first('order.cliente_id') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.order.fields.cliente_helper') }}
    </div>
</div>

<div class="form-group {{ $errors->has('product') ? 'invalid' : '' }}">
    <label class="form-label" for="product">{{ trans('cruds.order.fields.product') }}</label>
    <x-select-list class="form-control" id="product" name="product" wire:model="product" :options="$this->listsForFields['product']" multiple />
    <div class="validation-message">
        {{ $errors->first('product') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.order.fields.product_helper') }}
    </div>
</div>


<div class="form-group {{ $errors->has('order.nome') ? 'invalid' : '' }}">
    <label class="form-label" for="nome">{{ trans('cruds.order.fields.nome') }}</label>
    <input class="form-control" type="text" name="nome" id="nome" wire:model.defer="order.nome">
    <div class="validation-message">
        {{ $errors->first('order.nome') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.order.fields.nome_helper') }}
    </div>
</div>

<div class="form-group">
    <button class="btn btn-indigo mr-2" type="submit">
        {{ trans('global.save') }}
    </button>
    <a href="{{ route('admin.orders.index') }}" class="btn btn-secondary">
        {{ trans('global.cancel') }}
    </a>
</div>

Work fine, but i want composer my order about 3 different sub-order A, B, C because i have 3 different delivery: del-A, del-B and del-C.
i think it’s possible i have this situation in my table order, 3 line same client and 3 delivery (consegna in Ialyan)

enter image description here
but now i don’t understund other relationship..
i need 3 different table each for one delivery?
thanks