We are moving an older PHP project over to laravel. We are trying to post JSON to our api we created, but are not aware how to have the JSON be bound to a model. We added the model as a parameter to the function, it is created but none of the properties are set on it from the JSON. Does this type of model binding exist in laravel?
class CalculatorModel
{
/**
* Value A.
*
* @var integer
*/
public $A;
/**
* Value B.
*
* @var integer
*/
public $B;
}
class CalculatorController
{
// What is trying to be achieved.
public function add(CalculatorModel $model)
{
return Calculator::Add($model);
}
// What we are trying to avoid
// as there is a lot of properties/objects in our real world JSON
public function add(Request $request)
{
$a = $request->json()->all();
$m = new CalculatorModel();
$m->A = $a['A'];
$m->B = $a['B'];
....
return Calculator::Add($m);
}
}
// in reoutes/api.php
Route::post('add', 'API\CalculatorController@add');
// External library's class
class Calculator
{
public static function Add(CalculatorModel $m)
{
return $m->A + $m->B;
}
}
Simple JSON post
{
"A": 2,
"B": 2
}
In ASP.Net, we are able to add a [FromBody]
attribute to the parameter so that ASP.Net would bind the content body as the model instead of form content. We are looking for similar functionality in laravel.