I have this JSON data sent in HTTP body in a post request.
{
"id" : 238,
"title": "Its a title",
"description": "Its a description",
"target_price": 3000,
"date_of_availability": "16-02-2023",
"condition": "abc",
"latitude": "-31.953030",
"longitude": "115.853600",
"attributes": {
"list" : [
{
"title" : "Color",
"value" : "Red"
},
{
"title" : "Frame",
"value" : "Metal Frame"
}
]
}
}
I want attributes
to be stored in json
data type field. I can get value of all other fields in my controller but when i dd($request->attributes);
it show me empty Parameter Bag.
How can i get $request->attributes
and store it in my json
data type field of mysql.
This is my migration
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id('post_id')->generatedAs();
$table->string('title');
$table->text('description');
$table->integer('target_price')->nullable();
$table->date('date_of_availability')->nullable();
$table->string('condition')->nullable();
$table->decimal('latitude', 11, 8);
$table->decimal('longitude', 11, 8);
$table->json('attributes')->nullable();
$table->timestamps();
});
}
Here i am saving
$post = new Post();
$post->title = $data->title;
$post->description = $data->description;
$post->target_price = $data->target_price;
$post->date_of_availability = date("Y-m-d", strtotime($data->date_of_availability));;
$post->condition = $data->condition;
$post->latitude = $data->latitude;
$post->longitude = $data->longitude;
$post->attributes = $data->attributes;
$post->save();
This is the error i am getting for line $post->attributes = $data->attributes;
"message": "Object of class Symfony\Component\HttpFoundation\ParameterBag could not be converted to string",
CodePudding user response:
The Laravel request object uses magic methods to access the parameters that are passed in the body of the request. This only works if the Request
class doesn't already have a property of the same name.
The Illuminate\Http\Request
class extends the Symfony\Component\HttpFoundation\Request
class which has an explicit property called $attributes
:
/**
* Custom parameters.
*
* @var ParameterBag
*/
public $attributes;
If you want to explicitly get a property from the request body without using the magic method you can use the input
or json
methods:
$post->attributes = $request->json('attributes');