Laravel Request File Change - php

I have an issue for Request Laravel when i'm uploading file with key 'siup', the Request data shown like this:
"_token" => "Ab9zfuQn0rb0exCx7IdMcnAxQWi4iqWcfcDy319B"
"_method" => "PUT"
"first_name" => "first"
"last_name" => "aaa"
"email" => "black.y_+ta#email.com"
"province" => "11"
"city_id" => "38"
"address" => "asdasd"
"phone" => "1234567890"
"company_type" => "koperasi"
"company_name" => "qqq"
"company_address" => "qqq"
"pic" => "qqqa"
"position" => "qqq"
"siup" => UploadedFile {#30 ▶}
i want to do this to the request response
$request->merge(['siup'=>$myVar]);
but the key siup did not change. i want to change the siup value to insert it to database with laravel eloquent update.

The request data exposed by the Request object comes from two different sources: the query data and the files. When you dump the contents of the request data, it merges these two sources together and that is your output.
When you use the merge(), replace(), etc. methods, it is only manipulating the query data. Therefore, even though you're attempting to overwrite the siup data, you're actually only changing the siup key in the query data. The siup key in the files data is not touched. When you dump the contents of the request data again, the siup files data overwrites your siup query data.
You will save yourself a lot of trouble if you just get your data as an array, and then just use the array as needed. This is a lot safer and easier than trying to manipulate the Request object, and is probably a lot more along the lines of what you should be doing anyway.
Something like:
$data = $request->except('siup');
$data['siup'] = $myVar;
// now use your data array
MyModel::create($data);

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 Request can't get values of some key

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

Laravel Request Validation of an object

I would like to filter some data coming from an API payload in which i have to check if some certain part of the data is an object, such as this:
"object"{
"propety":value,
"another_propety":value,
}
I wanna be sure that the "object" that comes from the payload is actually an object, which holds properties and not an integer, neither, an array or any other type...but an object. Is there any way i can solve this by using Laravel's native validator i have to create a custom rule?
Thank you
Considering the laravel lifecycle, By the time the request payload reaches validation the object has already changed to a php array, use the below to validate your key.
$this->validate($request, [
'object' => 'required|array',
'object.property' => 'required|string',
]);
https://laravel.com/docs/5.8/validation#rule-array
also in case it is somehow going to remain a JSON object, check the official documentation for doing so -> https://laravel.com/docs/5.8/validation#rule-json
This will help you identify the object key as JSON while the request gets vaildated.

Redis and symfony PSR16 cache

I'm saving a value into Redis cache from a symfony application using Symfony\Component\Cache\Psr16Cache implementation. I do
$cache->set('key',[
'value1' => (new \DateTime())->getTimestamp(),
'value2' => (new \DateTime())->getTimestamp(),
'value3' => 'message'
])
Obviously two \Datetime's are different. What it does is kind of serialization of the array and datetime objects into string like :
127.0.0.10:6379> GET key
"\x00\x00\x00\x02\x14\x03\x11\x16value1\x17\bDateTime\x14\x03\x11\x04date\x11\x1a2019-09-25 09:12:00.000000\x11\rtimezone_type\x06\x03\x11\btimezone\x11\x10America/New_York\x11\x14value2\x1a\x01\x14\x03\x0e\x02\x11\x1a2019-09-28 20:39:00.000000\x0e\x04\x06\x03\x0e\x05\x0e\x06\x11\x13message\x11\x11message"
So it's type of string, not array.
Then I need to read this key from another app. This app uses this Redis class and its hgetall call, which returns (error) WRONGTYPE Operation against a key holding the wrong kind of value for the key I saved above from the other app.
Question: what call from Redis library should I use to get the array from the serialized value that PSR16 symfony implementation saved?

Best practices for read array from file in Laravel

My question might be stupid. But i need to clear my concept about it.
There are several ways to read array in Laravel. like config() variable , .env function, trans() function, file read like .csv, .txt, .json etc.
May be all of them are different purpose.
But i need to know what will be the good practice to read array data from my controller. An example given. Thanks
Example array:
[
"mohammad" => [
"physics" => 35,
"maths" => 30,
"chemistry" => 39
],
"qadir" => [
"physics" => 30,
"maths" => 32,
"chemistry" => 29
],
"zara" => [
"physics" => 31,
"maths" => 22,
"chemistry" => 39
]
]
Laravel uses var_export() under the hood to cache the config in this way:
$config = [
'myvalue' => 123,
'mysub' => [
'mysubvalue' => true
]
];
$code = '<?php return '.var_export($config, true).';'.PHP_EOL;
where $config can be a multidimensional associative array.
if you put that string into a file:
file_put_contents(config_path('myconf.php'), $code);
in the code you have to simply include that file to have your structure
$myconfig = require config_path('myconf.php');
dd($myconfig);
or (if is config file) call
echo config('myconf.myvalue');
To retrive values in Laravel style you can use the Illuminate\Config\Repository class
eg.
$conf = new Illuminate\Config\Repository($myconfig);
echo $conf->get('mysub.mysubvalue');
or
echo Illuminate\Support\Arr::get($myconfig, 'mysub.mysubvalue');
hope this will clarify and help
I don't know if this is best practice, but i can sure you that it's working, not just in Laravel but in any other PHP project.
That been said, to read an array from a file all you have to do is to include this file, the returned array you can assign it to a variable.
The array must be returned form the included file, it's important
Example:
path/to/my/array_file.php
<?php
return [
'resource' => [
'delete' => 'Are you sure you want to delete this resource?',
'updated' => 'Data for this resource has been successfully updated',
'created' => 'Data for this resource has been successfully created',
'deleted' => 'Data for this resource has been successfully deleted',
],
];
If i need to access this array any where in my project, i can include it like this:
$messages = include('path/to/my/array_file.php');
Now $messages is just another php array.
if you var_dump($messages) or dd($messages) in Laravel you get something like this:
array:2 [▼
"resource" => array:4 [▼
"delete" => "Are you sure you want to delete this resource?"
"updated" => "Data for this resource has been successfully updated"
"created" => "Data for this resource has been successfully created"
"deleted" => "Data for this resource has been successfully deleted"
]
]
Just a minor correction to the answer above: the author asked about reading the data, so they presumably need unserialize(file_get_contents('data.file')); However, I do support the answer above as it's really bad idea to store and read something from the filesystem, not only because of concurrent read/writes , but because of speed/file access/caching issues as well.
There are serialize() and unserialize() functions that creates/loads a textual representation of any php value.
However, I would use files for storing data ONLY if the data do not change much on runtime. E.g. for caching or configuration purposes. Otherwise, you may run into collisions when multiple sessions attempt to read/write the file at the same time and produce weird errors
http://php.net/manual/en/function.serialize.php
Responses to some of the comments by OP:
Laravel uses config files that are interpreted, i.e. parsed by the PHP once the framework boots up. Use of such files enable the use of some neat language features, such as class injection, allows to version the config files, and makes life somewhat easier for devs as the config pertaining framework stuff is stored in the code.
For runtime, session-specific stuff, use a database. There is $_SESSION[] variable for storing temporary data. Depending on your config the values could be stored in memory or files, and the PHP takes care of them.
I wanted to import a simple array from a file in a Laravel project . I saved the file in resources/appData and for loading the array I ended up in this:
$categories = include(resource_path('appData/categories.php'));
This will load the array from the file located in 'resources/appData/categories.php' and save it to the $categories variable.
The file returns an array like the config files in Laravel
<?php
return [
];
I don't know if this is a best practice though.

Categories