Vue
How to POST arrays with FormData in Vue and Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
オススメ本
When sending images in Vue and Laravel, you use FormData, but when you want to send an array at the same time, you need a little trick, so I wrote this article.
I also wrote about the validation method at that time.
⇨ Click here for the table of contents for Vue articles
Conclusion
Use JSON.stringify on the Vue side
formData.append("texts", JSON.stringify(this.texts))
Use json_encode on the Laravel side
$texts = json_decode($request->texts);
That's it.
Complete code
Vue
<template>
<v-btn @click="post">Test Send</v-btn>
</template>
<script>
export default {
data() {
return {
texts: [
{
name: "me",
content: "completely understood",
},
{
name: "me2",
content: "perfectly understood",
},
{
name: "me3",
content: "comprehensively understood",
},
{
name: "me4",
content: "fully understood",
},
{
name: "me5",
content: "totally understood",
},
{
name: "me6",
content: "kakakakaka",
},
],
}
},
methods: {
post() {
var formData = new FormData();
formData.append("texts", JSON.stringify(this.texts));
// Using this.texts directly turns it into a string, not an array
// formData.append("texts", this.texts);
// config is used when sending images
// omitted in this case for simplicity
var config = {
header: {
"Content-Type": "multipart/form-data",
},
};
axios
.post("api/post", formData, config)
.then(({ data }) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
},
}
}
Laravel
api.php
use App\Http\Controllers\Api\PostController;
Route::post('/post',[PostController::class, 'store']);
PostController
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$texts = json_decode($request->texts);
return response()->json(compact('texts'),200);
}
}
Validate with Form Request
PostRequest
// Override
public function validationData()
{
$texts = json_decode($this->input('texts'), true);
return $this->all() + ['array' => $texts];
}
// Check if the original data is in JSON format
//
public function rules()
{
return [
'texts' => 'json',
'array.*.name' => 'required|string',
'array.*.content' => 'required|string|max:1000'
];
}
PostController
public function store(PostRequest $request)
Related Articles
How to Save Images with Laravel + Vue + S3
Summary
I apologize for the code-heavy content!
If you have any complaints or corrections, please feel free to reach out via DM on Twitter below.
That's it!
Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!