API in Laravel receive JSON POST and write to database

2

I will receive through the API a JSON with this structure:

{"leads":
  [{"id":"1",
    "email":"[email protected]",
    "name":"Bruno Ghisi",
    "company":"Resultados Digitais",
    "job_title":"IT",
    "bio":"This is my bio",
    "created_at":"2012-06-04T15:31:35-03:00",
    "opportunity":"false",
    "number_conversions":"3",
    "first_conversion": {
      "content": {
        "identificador":"ebook-abc",
        "nome":"Bruno",
        "email_lead":"[email protected]",
        "telefone":"99999999",
        "empresa":"Resultados Digitais",
        "cargo":"IT"
      },
      "created_at":"2012-06-04T15:31:35-03:00",
      "cumulative_sum":"1",
      "source":"source 1"
    },
    "last_conversion": {
      "content": {
        "identificador":"webinar-abc",
        "email_lead":"[email protected]"
      },
      "created_at":"2012-06-04T15:31:35-03:00",
      "cumulative_sum":"2",
      "source":"source 2"
    }
  }]
}

My API should receive this data and write to my database, I'm starting to use Laravel and I followed a Vedovelli tutorial, the API is receiving and recording POSTs performed without being in the json format, but I'll test it in this format. inserts a row in the database by writing only the ID without the other information.

My Controller looks like this:

public function saveLead()
    {
        return Response::json($this->lead->saveLead(), 200);
    }

and the Model this way:

 public function saveLead()
    {
        $input = Input::all(); //pega todos os dados do input
        $lead = new Lead(); //criar um novo registro
        $lead->fill($input); //inclui todos os dados do input
        $lead->save(); //salva o input
        return $lead; //retorna o lead gravado
    }

If I add a dd ($ input); it shows me an array with the data, but at the time of writing it does not insert the values in the base.

Thanks in advance for anyone who can help me. :

    
asked by anonymous 25.03.2015 / 18:53

1 answer

1

I was able to resolve this:

public function saveConversion()
    {
        $input = file_get_contents('php://input'); // Pega todos os dados do json
        $jsonDecode = json_decode($input); // Decodifica o json e transforma em objeto
        $leads = $jsonDecode->leads[0];

        $lead->id = $leads->id;
        $lead->email = $leads->email;
        $lead->name = $leads->name;
        $lead->company = $leads->company;
        $lead->job_title = $leads->job_title;
        $lead->bio = $leads->bio;
        $lead->opportunity = $leads->opportunity;
        $lead->number_conversions = $leads->number_conversions;

        $lead->save(); // Salva o input

        return $lead; // Retorna o lead gravado
    }
    
30.03.2015 / 13:09