I need to add custom data to the request input array from my customRequest class
I tried this way
request()->request->add(['cool' => request()->get('var1').request()->get('var2')]);
It's do the trick with request()->all() but when I returned $request->validated() it's not exist.
how can I do it?
$request->validated() is returning only validated data (data in the request validator class).
After validating the data you can add additional data in the request using
$request->merge(['cool' => request()->get('var1')]);
Laravel documentation: https://laravel.com/docs/8.x/requests#merging-additional-input
I had the same problem and this is what I did, and it worked for me.
You can store the validated data in a variable as shown below.
$validated_data = $request->validated();
And then make your changes on the $validated_data variable as shown below.
$validated_data['cool'] = $request->input('var1').$request->input('var2');
This should add the extra data to the validated data.
I have done this way
protected function passedValidation()
{
$bar = 'test';
$validated = $this->validated();
$validated['foo'] = $bar;
$this->merge([
'mergedValidated' => $validated
]);
}
Then in Controller I did this
$request->mergedValidated
You can merge with new array
array_merge(request()->all(), ['cool' => request()->get('var1').request()->get('var2')]);
Related
I am using the Laravel framework to work with my MySQL database, and currently want to update my database from a JSON object, that will be sent from somewhere else.
Currently, I have it the same as my 'Store' function, which is obviously not going to work, because it will update everything, or refuse to work because it is missing information.
This is the for each I have currently, it does not work, but I am not experienced with how it is best to parse a JSON with a for-each, then store it.
public function update(Request $request,$student)
{
$storeData = User::find($student);
foreach ($request as $value) {
$storeData-> username = $value;
}
Here is my store function, with all the info that the front-end team may send in a JSON format.
$storeData->username=$request->input('username');
$storeData->password=$request->input('password');
$storeData->email=$request->input('email');
$storeData->location=$request->input('location');
$storeData->role=DB::table('users')->where('user_id', $student)->value('role');
$storeData->devotional_id=$request->input('devotional_id');
$storeData->gift_id=$request->input('gift_id');
$storeData->save();
return dd("Info Recieved");
You can write the method like the below snippet.
Also, assume you are working with laravel API, so you don't need to parse the incoming JSON input, but you will receive these values as items in the request object.
However, you should use the filled method in order to determine if the field is existing and has a value, the update function will override with empty values otherwise.
I just added this method to the first input, but you have to use it each and every input if you are not sure what the front end will pass.
public function update(Request $request, $student)
{
$storeData = User::find($student); // should be id
if ($request->filled('username')) { // use this for other items also
$storeData->username = $request->input('username');
}
$storeData->password = $request->input('password');
$storeData->email = $request->input('email');
$storeData->location = $request->input('location');
$storeData->role = DB::table('users')->where('user_id', $student)->value('role');
$storeData->devotional_id = $request->input('devotional_id');
$storeData->gift_id = $request->input('gift_id');
$storeData->update();
dd("Info Recieved");
}
Why would they send json data from the front in a post?
Really it would be from a form input. Like Rinto said it would be request object.
$user->username = $request->user_name;
I'm gathering this is a form on the front to create a new user. Why not use the built in auth scaffolding that has this set up for you in the register area?
So I'd personally use...
//look up user that matches the email or create a new user
$user = User::firstOrNew(['email' => request('email')]);
//add other input values here
$user->name = request('name');
//save
$user->save();
Hard to give an exact answer to this when the question is a bit vague in what you're doing. There are many methods in Laravel to accomplish things. From your code it just looks like registration. Also, the big gotcha I see in your code is you are passing a text only password and then adding that password in plain text to your database. That is a big security flaw.
you can convert your JSON object to an array and then do your foreach loop on the new array. To update a table in Laravel it's update ($storeData->update();) not save. Save is to insert.
$Arr = json_decode($request, true);
I would like to submit my form with many of fields.
As the documentation
$flight = new Flight;
$flight->name = $request->name;
$flight->param1 = $request->param1;
$flight->param2 = $request->param2;
...
$flight->param_n = $request->param_n;
$flight->save();
Its a bad idea if have too much fields.
I'm looking for any script like:
$flight = new Flight;
$flight->save($request->all());
But $request->all() function got unnecessary fields
What is the best way to do?
You could use the model $fillable array for this so long as your model properties match your request properties exactly.
$flight = new Flight();
$data = $request->only($flight->getFillable());
$flight->fill($data)->save();
You'll need to specify the fillable fields for any model that you would like to use this behavior for.
For Laravel 5.4 and lower use intersect instead of only
Otherwise you can just whitelist the properties you want from the request
$data = $request->only(['param1', 'param2' ...]);
There are various ways. you can exclude unwanted values as
$data = $request->except(['_token','_method','etc']);
The best way would be validated data. viz apply validation on your form inputs on server side.
$validated_data = $request->validate(['field1'=>'required','field2'=> 'required']);
etc. you can apply desired validations on each field and only validated fields will be in $validated_data variable, and then you can save them.
I'm implementing editing user profile via API. The page where user edits its data contains a lot of fields, but when user submits the form, only edited fields are sent to my API endpoint. Also I'm not using form mapping.
Only way I see is to write something like this:
public function editProfile(FormInterface $form, User $user): User
{
$args = $form->getData();
if ($args['email']) {
$user->setEmail($args['email']);
}
if ($args['phone']) {
$user->setPhone($args['phone']);
}
// ...
$this->em->persist($user);
$this->em->flush();
return $user;
}
But it looks terrible and my form may contain up to several tens of fields.
Does anybody know good solution for this case?
Use form mapping and submit form with disabled clear missing fields option:
In form builder:
$options->setDefaults([
'data_class' => MyEntity:class
]);
In controller:
$data = $request->request->all();
$form->submit($data, false);`
instead of $form->handleRequest($request);
Can someone enligthen me ,what is the real usage of load method if setting post params can be directly set to models attributes? Thanks
$model->load(Yii::$app->request->post());
vs
$model->attributes = Yii::$app->request->post();
As you can easy see in http://www.yiiframework.com/doc-2.0/yii-base-model.html#load()-detail
load Populates the model with input data. load() gets the 'FormName'
from the model's formName() method (which you may override), unless
the $formName parameter is given.
the data being populated is subject to the safety check by setAttributes().
see also http://www.yiiframework.com/doc-2.0/guide-structure-models.html
The main purpose of load($data, $formName) is to return boolean true if the expected $formName is found in $data. Thus, you can bypass the following:
if (isset($_POST['FormName'])) {
$model->attributes = $_POST['FormName'];
do_something_here;
}
with
$post = Yii::$app->request->post();
if ($model->load($post)) {
do_something_here;
}
It's interesting for more, different kind of models:
$post = Yii::$app->request->post();
if ($modelA->load($post) && $modelB->load($post) && $modelC->load($post)) {
do_something_if_all_models_are_loaded;
}
load() will only assign attributes that have got validation rules assigned to them in current scenario so you are able to verify them.
not sure if you have gone through this or not .. .but it's pretty much clear here : www.yiiframework.com/doc-2.0/yii-base-model.html#load()-detail
I am following tutorial http://www.tutorials.kode-blog.com/laravel-5-angularjs-tutorial and I have managed to write the similar method for my controller:
public function update(Request $request, $id) {
$employee = Employee::find($id);
$employee->name = $request->input('name');
//...
$employee->save();
return "Sucess updating user #" . $employee->id;
}
It is thought in tutorial that this code works but in reality var_dump($request->input) gives NULL. So - what $request variable should I use for getting the body of the request? I made var_dump($request) but the structure is unmanageably large. Actually I am suscpicous about this tutorial - do we really need to list all the fields in the standard update procedure?
You can access the input data with:
$input = $request->all();
https://laravel.com/docs/5.2/requests#retrieving-input
However, I've also had to get the input in this manner when using AngularJS $http module:
$input = file_get_contents('php://input');
for get all input
try it
$request = \Input::all();
If you want to fetch individual parameters from request object the you can do that with input Method of Request Class.
$request->input("parameter_name");
But if you want to fetch all request parameters then you can use all method which will return you an array of all the request key-value pairs
$request->all()
The thing you are missed is, you are calling $request->input which is null because input is method of Request class and not a property