Home > OS >  Posting data from Symfony 4 to Laravel 9
Posting data from Symfony 4 to Laravel 9

Time:09-23

I got this legacy Symfony 4 web app where I need to post an array of IDs to a Laravel web app.

I've been searching in late days and I can't get it to receive the posted data, since I always get NULL.

I have tested in Postman and it works fine. But posting the data right from Symfony 4, I just get null data or I can't find a way to receive that posted data.

I have both tried the Curl-less way and Curl and I still get empty data.

I firstly prefer the curl-less way, since I bet the server doesn't have the php-curl extension and it might be cumbersome to get it installed.

  1. Curl-less way ===============

From the Symfony app (the sender) I got postDataController.php

<?php

namespace App\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @route("/posting/test")
 */
class Post2WebhookController extends AbstractController
{
    /**
     * @route("/post2webhook", methods={"GET"}, name="post2webhook")
     * @Security("is_granted('ROLE_1') or is_granted('ROLE_2') or is_granted('ROLE_3')", message="error message.")
     * @return Response
     */
    public function post2webhook(){
        $ids = array(1,2,3,4,5,6);
        $url = "http://myLaravel9App.local/api/webhook";

        try{
            $result = $this->post($url,$ids);
            var_dump($result);
            //file_get_contents($url, false, $context);
        }
        catch(\Exception $e){
            echo '<p style="color: red;">Not connected. More details:  </p>'.$e->getMessage();
        }

        return new Response('success');//The response content must be a string. //https://stackoverflow.com/a/33422374/1883256
        //var_dump($result);
    }

    /* Send a POST request without using PHP's curl functions.
     *
     * @param string $url The URL you are sending the POST request to.
     * @param array $postVars Associative array containing POST values.
     * @return string The output response.
     * @throws Exception If the request fails.
     */
    public function post($url, $postVars = array()){
        //Transform our POST array into a URL-encoded query string.
        $postStr = http_build_query($postVars);
        //Create an $options array that can be passed into stream_context_create.
        $options = array(
            'http' =>
                array(
                    'method'  => 'POST', //We are using the POST HTTP method.
                    'header'  => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $postStr //Our URL-encoded query string.
                )
        );
        //Pass our $options array into stream_context_create.
        //This will return a stream context resource.
        $streamContext  = stream_context_create($options);
        //Use PHP's file_get_contents function to carry out the request.
        //We pass the $streamContext variable in as a third parameter.
        $result = file_get_contents($url, false, $streamContext);
        //If $result is FALSE, then the request has failed.
        if($result === false){
            //If the request failed, throw an Exception containing
            //the error.
            $error = error_get_last();
            throw new \Exception('POST request failed: ' . $error['message']);
        }
        //If everything went OK, return the response.
        return $result;
    }
}


From The Laravel app (the receiver) I got webHookController.php

<?php

namespace App\Http\Controllers\Constancias\Log;

use App\Http\Controllers\Controller;
use App\Notifications\Efirma\Constancias\Firmadas;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;

class ConstanciaFirmadaController extends Controller
{
    /**
     * Get the posted data from the symfony app.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function constancia_firmada(Request $request){
        $ids= $request->get('content');//IT ALWAYS RETURNS NULL!
        //dd($request->all());
        $tipo_contenido = gettype($request->get('content'));//gettype($ids);//IT ALWAYS RETURNS NULL!
        //dd(gettype($ids));
        Notification::route('mail',
                ['[email protected]'=>'Mr. John Doe']
            )
            ->notify(new Firmadas(content: $tipo_contenido))
        ;
    }
}
  1. Curl way (not preferred) =====================

What am I missing? How do I fix it?

CodePudding user response:

you need a key for the content

$this->post($url,['ids' => $ids]);

and in laravel:

$request->get('ids');
  • Related