Laravel Request can't get values of some key - php

I am trying to retrieve some part of request() in my Form Request class named StoreApplicantLanguage.php. The request key called 'languages' and it has an array of objects containing a key-value pair to be stored in my `applicant_languages' table.
Here is my JSON request from Postman:
{
"languages": [
{
"language": "English",
"capability": 1
}
]
}
Looks normal right?! But, when I'm trying to get the values of the languages key like this:
$requestLanguages = request()->languages;
dd($requestLanguages);
, it shows null.
I tried to restart my server, do php artisan config:cache, but none are works. But when I change the key name in the request object to language, it works!
Also, the request object has another named field like families, and I can get the values inside by doing request()->families.
I have no idea at all how this can be happen. Anyone can explain my case, please!
Thanks in advance!
Edit: From Malkhazi Dartsmelidze's answer I realized that I misstyped the question. I didn't write comma after '1' value in my JSON request

It works fine on my system.
Maybe you that's because you are passing invalid json.
{
"languages": [
{
"language": "English",
"capability": 1
}
]
}
Try passing this JSON (I deleted last comma after '1')
Also note that Request is object and there is properties that are used already and $request variable can return it. You can use $request->get('languages') to get parameter from request

Related

fetch associated Array in laravel/php

I m getting following response from a third party api using php. I want to retrieve "data" named key value. In simple words, I want to retrieve value of "#data". I have no idea why # sign is used with "data" named key.
array:1[
dataInfo: DataPartInfo {
#data: b"""
}
]

Laravel 5 API - Handle arrays

I am work with Laravel 5 and have implemented a working Restful API. I am trying to allow posts to be created by passing in an array like this...
post
title
excerpt
content
image
post
title
excerpt
content
image
The API currently works great for posting one individual post but how can I handle the array of posts instead?
Does anyone have an example I can see?
If you are using the Resource Controller, you should have a PostsController with a method store(). I am assuming your request payload is some JSON like this:
{"posts": [{"title":"foo"},{"title":"bar"}, …]}
So you need to json_decode the input. Then pass it to your database:
public function store()
{
$posts = json_decode($request->input('posts', ''));
if (is_array($posts)) {
DB::table('posts')->insert($posts);
}
}
There is probably some plugin or middleware or whatever to automatically decode the JSON payload. But apart from that, there is nothing special about doing what you ask for.
If you don't want to use the store() method (because it already stores a single Post or something) you can just add another route for your multiple Posts.
did you try to send JSON in the body? Here is a link with an example
Request body could look like the following:
{
"parameters":[
{
"value":{
"array":{
"elements":[
{
"string":{
"value":"value1"
}
},
{
"string":{
"value":"value2"
}
},
{
"string":{
"value":"value3"
}
}
]
}
},
"type":"Array/string",
"name":"arrayvariable"
}
]
}
This will convert the array every time you get it from the DB and every time you save it to the DB.
And here is an example using laravel casting link
Use attribute casting. Open your IdModel model and add this:
protected $casts = [
'id' => 'array' ];

Converting JSON to Doctrine Entity in Symfony

I'm currently working on building an API with the Symfony framwork. I've done enough reading to know to use the Serialization component, and built some custom normalizers for my entities. The way it currently works is:
JSON -> Array(Decode) -> User Entity(Denormalize)
This was working find as long as the request content was a JSON representation of the user, example:
{
"email": "demouser#email.com",
"plainPassword": "demouser",
"first_name" : "Demo",
"last_name" : "User"
}
A user entity is created using the following code in my controller:
$newuser = $this->get('api.serializer.default')->deserialize($request->getContent(), WebsiteUser::class, 'json');
However, I'd like to nest the user JSON in the 'data' property of a JSON object, which will allow consumers to pass additional metadata with the request, example:
{
"options": [
{
"foo": "bar"
}
],
"data": [
{
"email": "demouser#email.com",
"plainPassword": "demouser",
"first_name": "Demo",
"last_name": "User"
}
]
}
The main issue this causes is that the deserialization does not succeed because the JSON format has changed.
The only solution I've considered so far is to json_decode the whole request body, grab the 'data' element of that array, and pass the contents of the data element to the denormalizer (instead of the deserializer).
Is there a better way to solve this problem?
You should be able to get a specific key of your request body like follows:
$newuser = $this->get('api.serializer.default')->deserialize(
$request->request->get('data'), WebsiteUser::class, 'json'
);
If you are not able to retrieve the data from key without decoding your request body, look at this bundle, it consists in only one EventListener that replaces the request body after decode it.
You can easily integrate the same logic in your application, or requiring the bundle directly (which works well).

Cakephp Web Service issue on "add"

I am trying to setup a simple Restfull api using cakephp.
I followed the documentation from the Cakephp site.
But I am encountering the following issue.
I am using Postman plugin to test the Api calls.
I have a table called 'Categories' and in its controller have an action add().
public function add() {
if ($this->request->is('post')) {
$this->Category->create();
if ($this->Category->save($this->data)) {
$message = 'Saved';
}
else {
$message = 'Error';
}
$this->set(array(
'message' => $message,
'_serialize' => array('message')
));
}
}
and in db, I have Category table with schema (id (int 11, PK, A_I), name(varchar(40)), created (datetime), modified(datetime)).
So from postman I send POST requests to http://myProject/categories.json.
From my understanding when i send key:name and value: test, it must save into the database, which works fine. But I must get error when I replace the "key" with something other than name. i.e for exmaple key: name123 and value: test2, But this data too is getting saved in the db without any error except for the name field. i.e it is saving (id:some value, name:"", created:somevalue, modified:someValue)
I dont understand how. Any help will be greatly appreciated.
You will need to provide more info because what you say doesn't make sense. For example what do your posted data look like? Is there any kind of validation in the model? How do you expect a key/value pair to be stored in only one field (specifically name) in the DB?
What happens now is that you tell Cake to save the supplied data ($this->Category->save($this->data)) although you don't check (via cake's validation rules in the model or any other means) that it contains useful arguments and especially Category.name.
As computers will just do what you tell them to do and not what you imply or have in mind, it goes on and sends the calculated created/modified fields to the DB which in turn saves them with the autoincremented ID. Since name doesn't have a UNIQUE or NOT NULL field condition in the DB it is saved as NULL or empty string.

How send Chain Json with submit into a form

I'm new with programmation JQuery, Json into PHP.
my doubt is this:
I have a chain Json as the following example
[
{"idwork":"1","status":"to_do"},
{"idwork":"2","status":"in_process"},
{"idwork":"3","status":"testing"}
]
and this chain is lodged in a variable called "data". I want post this to a class, named operation where it receive this values idwork and status, to do a consultation into SQL.
Class operation
<?php
require_once('../../clases/tarea.php');
$operacion=$_REQUEST['operaciones'];
$tarea_temporal=new tarea($_REQUEST['idtarea'],'','',0,0,0,0,0,$_REQUEST['status']);
switch($operacion)
{
case 'Modificar':
$tarea_temporal->update_status();
break;
}
header('Location:../baraja/task.php.php');
?>
I want to know how to send this variable in a form
You can use json_decode, and then u can access the data like object or array... At doc u have an example:
http://es1.php.net/json_decode

Categories