Why Laravel REST controller $request->input is NULL? - php

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

Related

On a Laravel 'update' function, how to parse a JSON object, and store it with a ForEach loop

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);

how to add data to validated request input bag

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')]);

Copy one row from one table to another

I need a little help and I can’t find an answer. I would like to replicate a row from one data table to another. My code is:
public function getClone($id) {
$item = Post::find($id);
$clone = $item->replicate();
unset($clone['name'],$clone['price']);
$data = json_decode($clone, true);
Order::create($data);
$orders = Order::orderBy('price', 'asc')->paginate(5);
return redirect ('/orders')->with('success', 'Success');
}
and i got an error :
"Missing argument 1 for
App\Http\Controllers\OrdersController::getClone()"
.
I have two models: Post and Order. After trying to walk around and write something like this:
public function getClone(Post $id) {
...
}
I got another error
Method replicate does not exist.
Where‘s my mistake? What wrong have i done? Maybe i should use another function? Do i need any additional file or code snippet used for json_decode ?
First of all, make sure your controller gets the $id parameter - you can read more about how routing works in Laravel here: https://laravel.com/docs/5.4/routing
Route::get('getClone/{id}','YourController#getClone');
Then, call the URL that contains the ID, e.g.:
localhost:8000/getClone/5
If you want to create an Order object based on a Post object, the following code will do the trick:
public function getClone($id) {
// find post with given ID
$post = Post::findOrFail($id);
// get all Post attributes
$data = $post->attributesToArray();
// remove name and price attributes
$data = array_except($data, ['name', 'price']);
// create new Order based on Post's data
$order = Order::create($data);
return redirect ('/orders')->with('success', 'Success');
}
By writing
public function getClone(Post $id)
you are telling the script that this function needs a variable $id from class Post, so you can rewrite this code like this :
public function getClone(){
$id = new Post;
}
However, in your case this does not make any sence, because you need and integer, from which you can find the required model.
To make things correct, you should look at your routes, because the url that executes this function is not correct, for example, if you have defined a route like this :
Route::get('getClone/{id}','YourController#getClone');
then the Url you are looking for is something like this :
localhost:8000/getClone/5
So that "5" is the actual ID of the post, and if its correct, then Post::find($id) will return the post and you will be able to replicate it, if not, it will return null and you will not be able to do so.
$item = Post::find($id);
if(!$item){
abort(404)
}
Using this will make a 404 page not found error, meaning that the ID is incorrect.

Laravel Request doesn't have parameters

I have a route like this:
Route::get('page/{id},{time}', 'OpController#op');
Now my method is simply:
public function op(Request $request, $id, $time)
{
dump($request->all());
dump($id);
}
If I call that with /op/hello,123 I get this dump:
$request->all() -> []
$id -> "hello"
Is there any reasons that $request doesn't have the parameters?
$request->input('id') returns null
Because Request shouldn't have URL vars in it. Request used for getting data from forms etc. You should use $id and $time variables if you want to get data from URL in this case.
You can contents of Request object by using dd($request);
Got it:
$request->input('param');
Works when url query param, example: url?param=text and all the params of POST.
That doesn't work with route param 'myurl/{param}'
Just change your route with below code....
Route::get('page/{id}/{time}', 'OpController#op');
And write url like /page/hello/123

Difference between get() and all() in laravel

What is difference between these two in laravel
$input = Input::get();
And
$input = Input::all();
And which one i should prefer.
Taken from the laravel source:
public static function all()
{
$input = array_merge(static::get(), static::query(), static::file());
// ....
return $input;
}
So all() calls get() and returns it's contents along with query(), and file() the $_FILES superglobal.
Preference will obviously depend on circumstance. I personally choose to use Input::get($key, $default) as I usually know what I am after.
From the Laravel Manual: http://laravel.com/docs/input
Retrieve a value from the input array:
$email = Input::get('email');
Note: The "get" method is used for all request types (GET, POST, PUT, and DELETE), not just GET requests.
Retrieve all input from the input array:
$input = Input::get();
Retrieve all input including the $_FILES array:
$input = Input::all();
By default, null will be returned if the input item does not exist. However, you may pass a different default value as a second parameter to the method:

Categories