Laravel 6 Form Array $request->input() doesn't work - laravel

I have this array of prices, like so:
<input type="input" id="prices[type][1]" name="prices[type][1]">
<input type="input" id="prices[type][2]" name="prices[type][2]">
I send this data via a post request (JSON: Yes, the Content-Type is set to application/json) and expected to get an array when I use $request->input('prices') but that doesn't really happen. Also tried $request->get('prices').
When I do $request->all() I do get all the data I submitted:
JS Used to make request:
const response = await fetch(this.action, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': this.$page.token,
},
body: this.formData(),
});
const body = await response.json();
this.formData():
formData(): Object {
const formData = new FormData(this.$el);
return JSON.stringify(Array.from(formData.entries()).reduce((memo, pair) => ({
...memo,
[pair[0]]: pair[1],
}), {}));
},
Does anyone have an idea on where it might go wrong?

Hm, it looks like the array is broken even if you do all() as I don't see the type key in the array.
Try this instead:
dd(json_decode($request->getContent(), true));
As it is JSON so you will need to get the body and convert it into an array.

You need to use:
$prices_array = $request->only('prices');
Or:
$no_prices_array = $request->except('prices');
That way you can filter a request by field, and access them.

Related

How to POST correctly a form that have data and files with VueJS, Axios and Laravel?

I am posting here as a beginner of VueJS and Laravel. I am stuck with a problem that I can't fix by myself after hours of search.
I would like to know how correctly send and get back the inputs of a form (complex data and files).
Here is the submit method of the form:
onSubmit: function () {
var formData = new FormData();
formData.append("data", this.model.data);
formData.append("partData", this.model.partData);
if (this.model.symbolFile != null) {
formData.append("symbolFile", this.model.symbolFile);
}
if (this.model.footprintFile != null) {
formData.append("footprintFile", this.model.footprintFile);
}
axios
.post("/api/updatecomponent", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
},
The variable Data and PartData contains multiple string fields which will be stored in different tables in my database. Example :
Data
{
string Value,
string Tolerance,
string Power
}
Here is the method of the Controller in the server side:
public function updateComponent(Request $req)
{
$data = $req->input('data');
$partData = $req->input('partData');
$symbolFile = $req->file('symbolFile'); // is null if the user did not modify the symbol
$footprintFile = $req->file('symbolFile'); // is null if the user did not modify the footprint
// etc...
}
I am able to get the files, everything work for that and I can store and read them :)
But, the problem is that I am unable to get back properly my Data or PartDat.
When I do :
dd($partData);
I got as result in the console:
"[object Object]"
I am almost sure that I don't use correctly the FormData but after hours of search, I can't find the good way I should gave the Data and PartData to the FormData.
My code was working well for Data and PartData until I add FormData to support the file upload :(
Thank you for your help :)
Here my working code:
Client side:
var formData = new FormData(); // create FormData
formData.append("subcat", this.subcategory);// append simple type data
formData.append("data", JSON.stringify(this.model.data));// append complex type data
axios // send FormData
.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
Server side:
public function createComponent(Request $req)
{
$subcategory = $req->input('subcat'); // get the input parameter named 'subcat' (selected subcategory)
$data = json_decode($req->input('data'), true); // get the input, decode the jason format, force to return the result as an array
}
I hope it will help other peoples :)
Simple solution
let data = new FormData();
data.append('image',file_name.value);
_.each(form_data, (value, key) => {
data.append(key, value)
})
console.log('form data',data);
Now you can get data in laravel controller like:
$request->title
$request->description
$request->file

Cannot upload image to laravel from react-native

I'm trying to let the user upload an image through react-native, but apparently, laravel is not being able to read any value from the request. This is what I'm trying to do with axios:
const data = new FormData()
data.append('subject_id', this.props.navigation.getParam('id'))
data.append('name', this.state.title)
// I don't think the path is enough, it will probably just send the path as a string instead of the image. You need to load the actual file and append that
data.append('image', {
uri: this.state.image,
type: 'image/jpeg',
name: 'image'
});
data.append('progress', this.state.progress * 100)
data.append('description', this.state.description)
data.append('date', this.state.date)
axios.post('https://example.com/api/auth/storeTask', data, {
headers: {
'Authorization': access,
"Content-Type": "multipart/form-data"
},
}).then(result => { })
.catch(err => console.warn)
The image is not found when I try to access the resource.
You should use a FormData object:
const data = new FormData()
data.append('subject_id', this.props.navigation.getParam('id'))
data.append('name', this.state.title)
// I don't think the path is enough, it will probably just send the path as a string instead of the image. You need to load the actual file and append that
data.append('image', this.state.image)
data.append('progress', this.state.progress * 100)
data.append('description', this.state.description)
data.append('date', this.state.date)
axios.post('https://example.com/api/auth/storeTask', data, {
headers: {
'Authorization': access,
"Content-Type": "multipart/form-data"
},
}).then(result => {})
.catch(err => console.warn)
You didn't send complete info like responses and logs, by the way,
Please check this instruction:
make sure your CSRF in verifyCSRFtoken is allowed
use FormData to upload your file
your code coulde be like this:
import axios, { post } from 'axios';
const url = '/uploadPic';
const formData = new FormData();
formData.append("image", {
name: this.state.photo.fileName,
type: this.state.photo.type,
uri: this.state.photo.uri,
});
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
for react native:
if you are in production and using react-native bare, you should add
<application
...
android:usesCleartextTraffic="true"
...
to your android file.

How to pass the Query Data in Body for making REST API call in graphql

I am doing a post operation where i am getting some response.
My URl looks Like:
http://domainname/api/v1:id
As a part of body i want to pass the below data:
{ elemetnt { id, name } }
Can anybody suggest me how i can achieve this.
i am trying with the below code but i am getting 404:
let queryParam = `{ elemetnt { id, name } }`;
this.http.post(`http://domainname/api/v1:1`, {
query: queryParam,
}, {
headers: new Headers({
'Content-Type': 'application/graphql',
}),
})
.catch((error: Response | any) => {
console.log(error);
return Observable.of(error);
})
.subscribe((res) => {
console.log(JSON.stringify(res));
});
I know i am doing something wrong. But, if somebody can help me on this then it would be great help.
It depends on method which receiving this data, but this is correct format for you as given in question
queryParam= { element : { id: "0000" , name: "name" };
you may need to stringy your solution
Canyou please try with
'Content-Type': 'application/json'
and pass json body like
{"query":"{ elemetnt { id, name } }" }
I think this may help you

React/redux app function not firing

Update 2:
Another update - I'm down to this one issue. The values from redux-form are being sent to the action, but even narrowed down to this:
export function signinUser(values) {
console.log('function about to run, email: ' values.get('email'));
}
I don't even see a console log entry. However, the same function with only a simple console log works:
export function signinUser() {
console.log('function about to run');
}
Update:
The only differences between the working code and non-working code is redux-form and immutablejs. I tried back-porting these to the working app and now the behaviour is the same.
I'm submitting my form and sending the redux-form values to the function, where I'm using values.get('email') and values.get('password') to pass the values to axios.
handleFormSubmit(values) {
console.log('sending to action...', values);
this.props.signinUser(values);
}
I have a login form and onSubmit I'm passing the values to a function which dispatches actions.
The code works in a repo I've forked, but I'm transferring it to my own app. The problem I'm having is that the function doesn't seem to fire, and I'm struggling to figure out where to add console.log statements.
The only console.log that fires is on line 2.
export function signinUser(values) {
console.log('function will run');
return function(dispatch) {
axios.post(TOKEN_URL, {
email: "a#a.com",
password: "a",
method: 'post',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
})
.then(response => {
console.log('response: ', response.data.content.token );
// If request is good...
// - Update state to indicate user is authenticated
dispatch({ type: AUTH_USER });
// decode token for info on the user
var decoded_token_data = jwt_decode(response.data.content.token);
// - Save the JWT token
localStorage.setItem('token', response.data.content.token);
console.log(localStorage.getItem('token'));
// - redirect to the appropriate route
browserHistory.push(ROOT_URL);
})
.catch(() => {
// If request is bad...
// - Show an error to the user
dispatch(authError('Bad Login Info'));
});
}
}

return multiple json encoded array from the server

I want to know how can I return multiple encoded JSON array from the server
ex.
//client
$.ajax({
url: 'items-details.php',
type: 'POST',
data: {member_id: 1},
dataType: 'html',
success: function(responseText) {
}
});
//server, items-details.php
//some code here
then, the final output is ex. itemsData array and itemsCategories array, then I use json_encode() on both array. but how can I return both arrays to the client? I only know how to handle echo() - which is treated by the client as string
before, I only use
echo(json_encode(itemsData));
then the client will parse it .. but how can I return multiple json encoded array: itemsData and itemsCategories
For example, you could create let's say a $response array, which could contain both the $itemsData and $itemsCategories arrays.
// $itemsData and $itemsCategories defined here
$response = array(
$itemsData, $itemsCategories
);
return json_encode($response);
You can create a json object that holds both or your arrays and json_encode that object and render that: json_encode(items = { data: itemsData, categories: itemsCategories })
#edgeofmystery, you get right answer but if you return assoc array it will be easier / more comfortable to parse it
$response = array(
"itemsData"=>$itemsData, "itemsCategories"=>$itemsCategories
);
echo json_encode($response);

Resources