adding manul data to form requests in laravel - laravel

I have this fuction which is getting data from my form add create row in database
$project = Project::create($request->only(['title', 'report_type', 'user_id', 'body', 'attachment', 'projectclass', 'budget', 'deadline']));
now I want add another data into it but that data not coming from form it generates in controller,
'pnum' => mt_rand(1000, 9223372036854775807)
How can I add my pnum data to the function above?

Take request data into variable which will be of type array and add there your new element
$insertData = $request->only(['title', 'report_type', 'user_id', 'body', 'attachment', 'projectclass', 'budget', 'deadline']);
$insertData['pnum'] = mt_rand(1000, 9223372036854775807);
Now you can pass this variable to create method
$project = Project::create($insertData);

first keep all the the data of your request to the variable eg: $data
and then follow the following
$data= $request->all();
$data['pnum'] = mt_rand(1000, 9223372036854775807);
$project = Project::create($data);

Related

store and update an array as json in mysql database laravel 9

I have values that I want to store in the database, I have declared the type as json and cast it as an array:
protected $casts = [
'favourites' => 'array'
];
however, I'm not sure how to add and update and read the values inside, any ideas?
controller function:
public function addtofav()
{
$id = request()->get('id');
$user = auth()->user();
json_decode($user->favourites,true);
array_push($user->favourites,$id);
dump('hello');
json_encode($user->favourites);
$user->save();
return response(['id'=> $id],200);
}
Quoting from the Laravel documenations:
adding the array cast to that attribute will automatically deserialize
the attribute to a PHP array when you access it on your Eloquent
model.
therefore, no need to make any encoding or decoding to your values before any update or create, just keep it as an array and Eloquent will take care of that, since you have the $cast array as below:
protected $casts = [
'options' => 'array',
];
Actually you should use many to many but if you want to use array, you don't encode or decode.
public function addtofav()
{
$id = request()->get('id');
$user = auth()->user();
$favourites = $user->favourites;
array_push($favourites,$id);
$user->favourites = $favourites
$user->save();
return response(['id'=> $id],200);
}

How to directly access JSON data as an object

I have a table where one of the columns has the data type "json". The column is called payment_data and inside of it I have a JSON object:
{"success":true,"status":0,"resposta":"OK","referencia":"44304425","entidade":"5555"}
I found an example online that I could call directly in Laravel, using this example:
{{ $order['payment_data->entidade']}}
But it doesn't work so I guess it is not right. Is there a helper available to get the information directly?
You have to override cast variable in your model:
protected $casts = [
'payment_data' => 'object'
];
Then you can use like this:
{{ $order->payment_data->entidade }}
You can use attribute casting on your model which would allow you to access the JSON data as an array.
For example, you can add the following to your your model class:
protected $casts = [
'payment_data' => 'array',
];
Then you should be able to access values inside the JSON value like this: $order->payment_data['entidade'].
try:
$order = new Order::find( 1 );
$json_data = json_decode( $order->payment_data );
echo $json_data->entidade;
If you have a json like this
{"success":true,"status":0,"resposta":"OK","referencia":"44304425","entidade":"5555"}
you can do like this to access the values
$json = {"success":true,"status":0,"resposta":"OK","referencia":"44304425","entidade":"5555"}
the you can access the values like this
$json = json_decode($json, true);
echo $json['entidade'];
I hope it helps some one,this how i solved my problem.

how to update json key value in laravel

we try to update the json data key value.we stored record in database product_name column like
{"ar":"arabic product","en":""}
we try to achieve this both below two method
DB::table('products')
->where('id', 1)
->update(['productname->en' => 'english product']);
$post = product::find($product_id);
$post->product_name = [$language => $edittitle];
$post->save();
we want to update the json en key value.
A quick and easy solution to update all the entries in one go:
Product::each(function ($product) {
$productName = json_decode($product->product_name, true);
$productName['en'] = 'english product';
$product->product_name = json_encode($productName);
$product->save();
});
If you want to update a single product, this should work:
$product = Product::find($product_id);
$productName = json_decode($product->product_name, true);
$productName['en'] = 'english product';
$product->product_name = json_encode($productName);
$product->save();
First thing is to create that field with the right type in the migration file, the keyword we need there is json:
...
$table->json('productname');
...
Then we need to cast that attribute to the right type when retrieving it as Eloquent model by using $casts attribute on the model itself:
...
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'productname' => 'array'
];
...
Then we can access and save data for this attribute like so:
$myModel = product::find(1);
$myModel->productname['en'] = 'something';
// or
$myModel->productname = ['en' => 'something']; // This will override the whole attribute
For further details you can take a look at: https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting

yii2 get getter's value in active query request (using asArray())

I have the next code:
$fixed_events = EventMain::find()
->select(["id", "title", "files"])
//->joinWith(['files'])
//->with(['files'])
->asArray()
->all();
How can i get array with "files" value, taking into account, that the "files" is modle's getter like
public function getFiles()
{
return (json_decode($this->all_files, true)) ?: [];
}
Since files is not a relation with EventMain table, I guess the easiest approach would be handle the data and convert with ArrayHelper after coming from db:
<?php
use yii\helpers\ArrayHelper;
$models = EventMain::find()->select(['id', 'title'])->all();
$array = ArrayHelper::toArray($models, [
'app\models\EventMain' => ['id', 'title','files']
]);
var_dump($array);
?>

How to change value of a request parameter in laravel

I need to change value of my request parameter like this:
$request->name = "My Value!";
I use this code but does not work:
$request->offsetSet('img', $img);
Try to:
$requestData = $request->all();
$requestData['img'] = $img;
Another way to do it:
$request->merge(['img' => $img]);
Thanks to #JoelHinz for this.
If you want to add or overwrite nested data:
$data['some']['thing'] = 'value';
$request->merge($data);
If you do not inject Request $request object, you can use the global request() helper or \Request:: facade instead of $request
Use merge():
$request->merge([
'user_id' => $modified_user_id_here,
]);
Simple! No need to transfer the entire $request->all() to another variable.
Read more about Laravel's merge() here:
https://laravel.com/docs/collections#method-merge
If you need to customize the request
$data = $request->all();
you can pass the name of the field and the value
$data['product_ref_code'] = 1650;
and finally pass the new request
$last = Product::create($data);
If you need to update a property in the request, I recommend you to use the replace method from Request class used by Laravel
$request->replace(['property to update' => $newValue]);
Use add
$request->request->add(['img' => $img]);
If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().
namespace App\Http\Requests\Admin\Category;
class CategoryRequest extends AbstractRequest
{
protected function prepareForValidation()
{
if ( ! $this->get('url')) {
$this->merge([
'url' => $this->get('name'),
]);
}
$this->merge([
'url' => \Str::slug($this->get('url')),
'active' => (int)$this->get('active'),
]);
}
}
I hope this information will be useful to somebody.
It work for me
$request = new Request();
$request->headers->set('content-type', 'application/json');
$request->initialize(['yourParam' => 2]);
check output
$queryParams = $request->query();
dd($queryParams['yourParam']); // 2
Great answers here but I needed to replace a value in a JSON request. After a little digging into the code, I came up with the following code. Let me know if I'm doing something dumb.
$json = $request->json()->all();
$json['field'] = 'new value';
$request->json()->replace($json);
Try that :
$request["name"] = "My New Value";
$request["img"] = $img;
It's worked in Laravel 8.
Also, make sure to update the model class.
Item
{
fillable=[
'img',
... // other attributes
];
}
in case of updating an item of object you can write the lines bellow
$Obj = $request->data;
$Obj['item'] = value;

Resources