如何检索 Ajax 在 laravel 中发送的对象数组
How to retrieve array of objects sent by Ajax in laravel
我将 Laravel 与 Vuejs 和 AXIOS 一起用于 HTTP 请求。我正在发送带有对象数组的 post 请求。那么在我的 laravel 存储函数中,如何从 $request?
中检索数据?
我的问题数组如下所示:
data:{
questions:[{
question:'',
opt1:''
},
{
question:'',
opt1:''
}
]
}
Laravel 控制器中的存储方法:
public function store(Request $request)
{
return $request;
}
vue 代码:
axios.post('/addTest',this.$data.questions).then(response=>{
console.log(response.data);
});
在此代码中问题是一个对象数组。
如果this.$data.questions
是一个数组,你可以简单地使用input()
方法来提取所有的问题:
$questions = $request->input();
假设你只想拉取第二项的 question
属性,你可以像 Laravel:
那样做
$secondQuestion = $request->input('1.question');
但是,如果您将问题作为对象传递也很好:
axios.post('/addTest', { questions: this.$data.questions });
您的 PHP 部分将如下所示:
$questions = $request->input('questions');
希望这能给你一些想法。
在 Laravel 中你有一个存储方法然后你返回请求?你为什么这样做?从前端查看请求?如果是这样,那么我建议您为此使用 postman。
Postman 易于使用,您可以在 laravel 存储功能中发送与前端 sends.Then 类似的请求
dd($request) //to output the request that postman sends
You said: how can I retrieve that data from the $request
如果你从前端发送类似
{ id: 1 }
然后在laravel你可以做
$id = $request->get('id');
Below you can see how i send a request with postman,and how output the request.
Your request with postman
Laravel code to output request
The response from Laravel displayed in postman
我将 Laravel 与 Vuejs 和 AXIOS 一起用于 HTTP 请求。我正在发送带有对象数组的 post 请求。那么在我的 laravel 存储函数中,如何从 $request?
中检索数据?我的问题数组如下所示:
data:{
questions:[{
question:'',
opt1:''
},
{
question:'',
opt1:''
}
]
}
Laravel 控制器中的存储方法:
public function store(Request $request)
{
return $request;
}
vue 代码:
axios.post('/addTest',this.$data.questions).then(response=>{
console.log(response.data);
});
在此代码中问题是一个对象数组。
如果this.$data.questions
是一个数组,你可以简单地使用input()
方法来提取所有的问题:
$questions = $request->input();
假设你只想拉取第二项的 question
属性,你可以像 Laravel:
$secondQuestion = $request->input('1.question');
但是,如果您将问题作为对象传递也很好:
axios.post('/addTest', { questions: this.$data.questions });
您的 PHP 部分将如下所示:
$questions = $request->input('questions');
希望这能给你一些想法。
在 Laravel 中你有一个存储方法然后你返回请求?你为什么这样做?从前端查看请求?如果是这样,那么我建议您为此使用 postman。
Postman 易于使用,您可以在 laravel 存储功能中发送与前端 sends.Then 类似的请求
dd($request) //to output the request that postman sends
You said: how can I retrieve that data from the $request
如果你从前端发送类似
{ id: 1 }
然后在laravel你可以做
$id = $request->get('id');
Below you can see how i send a request with postman,and how output the request.
Your request with postman
Laravel code to output request
The response from Laravel displayed in postman