Vue.js with Laravel 8 API image upload throws 500 error - laravel

Below is this code for the image upload path; this is my template upload code.
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
<input #change="onFileSelected" class="custom-file-input" type="file">
<small class="text-danger" v-if="errors.photo"> {{errors.photo[0]}} </small>
<label accept="image/*" class="custom-file-label" for="customFile" id="photo">Choose file</label>
</div>
<div class="col-md-6">
<img :src="form.photo" style="height: 40px; width:40px;">
</div>
</div>
</div>
This is the click event's function; this is the data I want to pass to my API.
ata() {
return {
form:{
name: null,
email: null,
address: null,
salary: null,
joining_date: null,
nid: null,
phone: null,
photo: null
},
errors: {
}
}
},
methods: {
onFileSelected(event){
// console.log(event)
let file = event.target.files[0];
if(file.size > 1048770) {
// Notification.image_validation()
Toast.fire({
icon: 'error',
title: 'upload image less than 1MB'
})
}else {
//console.log(form)
let reader = new FileReader();
reader.onload = event =>{
this.form.photo = event.target.result
console.log(event.target.result)
};
reader.readAsDataURL(file)
}
},
The following is the code I push my date to.
employeeinsert()
{
console.log(this.form.photo)
axios.post('/api/employee', this.form)
.then(() => {
// console.log(this.form)
// this.$router.push({name: 'employee'})
// Toast.fire({
// icon: 'success',
// title: 'employee add success'
// })
})
.catch(error => this.errors = error.response.data.errors)
}
These are the Laravel 8 backend validations. Here I try to get the request image and name change and try to save my public folder.
if ($request->photo) {
$position = strpos($request->photo, ';');
$sub = substr($request->photo, 0, $position);
$ext = explode('/', $sub)[1];
$name = time() . "." . $ext;
$img = Image::make($request->photo)->resize(240, 200);
$upload_path = 'backend/employee';
$inage_url = $upload_path . $name;
$img->save($inage_url);
return console . log($inage_url);
Employee::insert([
'name' => $request->name,
'email' => $request->email,
'address' => $request->address,
'salary' => $request->salary,
'joining_date' => $request->joining_date,
'nid' => $request->nid,
'phone' => $request->phone,
'photo' => $last_image
]);
When I upload an image, I get a 500 error.
Here's the 500 error with any logs.
I have no idea why it throws 500. Please help to resolve this.

Few things which can cause 500 error as visible in your code are
return console.log($inage_url): console.log() is javascript not PHP
$inage_url = $upload_path.$name; it should be $inage_url = $upload_path.'/'.$name otherwise $img->save($inage_url); can cause error as path is not well formed
Not clear where the $last_image comes from in'photo' => $last_image

Related

Laravel and upload image more than 2MB

I am trying to upload pdf files larger than 2mb with no success.
Changed php.ini settings, server timeout but still got an error.
Let's see some code:
This is the function on Controller
public function saveImage(Request $request)
{
// return $request->all();
$consorciado = User::where('cpfCnpj', '=', $request->consorciado_id)->first();
$documento = Documento::where('cad_doc_id', '=', $request->id)->first();
$documento = new Documento();
$image = request()->file('f');
$documento->user_id = $consorciado->id;
$documento->cad_doc_id = $request->id;
$documento->remark = $request->remark;
$documento->idTematica = $request->idTematica;
$documento->field1 = $request->field1;
$documento->field2 = $request->field2;
$documento->field3 = $request->field3;
$documento->field4 = $request->field4;
$documento->field5 = $request->field5;
$filename = $request->field1 . "_" . $request->field2 . "_" . $request->field3 . "." . $image->getClientOriginalExtension();
$documento->nome = $filename;
Storage::disk('local')->put('public/' . $filename, file_get_contents($image), 'public');
$documento->save(); //salva no meu banco
$client = new Client([
'base_uri' => 'https://gedms.gedocflex.com.br/api/file',
]);
$response = $client->request('POST', 'https://gedms.gedocflex.com.br/api/file', [
'multipart' => [
[
'name' => 'idTematica',
'contents' => $request->idTematica
],
[
'name' => 'f',
'contents' => fopen(storage_path() . "/app/public/" . $filename, 'r')
// 'contents' => fopen('http://18.191.51.177/storage/' . $filename, 'r')
],
[
'name' => 'field1',
'contents' => $request->field1
],
[
'name' => 'field2',
'contents' => $request->field2
],
[
'name' => 'field3',
'contents' => $request->field3
],
[
'name' => 'field4',
'contents' => $request->field4
],
[
'name' => 'field5',
'contents' => $request->field5
],
[
'name' => 'remark',
'contents' => 'CARTA'
],
]
]);
return $response;
}
The upload form is an VueJS component and the code is:
<template>
<div class="form-group col">
<label class="custom-file">
<slot></slot>
<input
type="file"
name="f"
class
#change="GetImage"
accept="image/jpeg, image/gif, image/png, application/pdf"
:required="required"
/>
<img :src="avatar" alt="Imagem" class="drop" />
<a
href="#"
v-if="loaded"
#click="ligaSpinner"
class="btn btn-success m-t-10"
#click.prevent="Upload"
>
<div v-if="spinner" class="spinner-grow spinner-grow-sm" role="status">
<span class="sr-only">enviando...</span>
</div>Enviar
</a>
Cancelar
</label>
<span class="custom-file-control text-muted"></span>
</div>
</template>
<script>
export default {
props: [
"consorciado_id",
"id",
"name",
"remark",
"idTematica",
"field1",
"field2",
"field3",
"field4",
"field5",
"required"
],
data() {
return {
avatar: "http://18.191.51.177/imagens/doc_original.png",
loaded: false,
consorciado: this.consorciado_id,
spinner: false,
reload: null
};
},
methods: {
ligaSpinner() {
this.spinner = true;
},
GetImage(e) {
let f = e.target.files[0];
this.Read(f);
let id = this.consorciado;
let doc_id = this.id;
let remark = this.remark;
let idTematica = this.idTematica;
let field1 = this.field1;
let field2 = this.field2;
let field3 = this.field3;
let field4 = this.field4;
let field5 = this.field5;
let form = new FormData();
form.append("f", f);
form.append("consorciado_id", id);
// form.append("tipo", tipo);
form.append("id", doc_id);
form.append("remark", remark);
form.append("idTematica", idTematica);
form.append("field1", field1);
form.append("field2", field2);
form.append("field3", field3);
form.append("field4", field4);
form.append("field5", field5);
this.file = form;
},
Upload() {
axios
.post(
"/saveImage",
this.file,
// this.tipo,
this.doc_id,
this.remark,
this.idTematica,
this.field1,
this.field2,
this.field3,
this.field4,
this.field5
)
.then(res => {
this.reload = true
this.$toasted
.show("Documento enviado com sucesso!", {
type: "success"
})
.goAway(3000);
this.loaded = false;
this.ligaSpinner = false;
});
},
Read(f) {
let reader = new FileReader();
reader.readAsDataURL(f);
reader.onload = e => {
this.avatar = "http://18.191.51.177/imagens/doc_pdf.png";
};
this.loaded = true;
},
Cancel() {
(this.avatar = "http://18.191.51.177/imagens/doc_original.png"),
(this.loaded = false);
}
}
};
</script>
The error:
message: "file_get_contents(): Filename cannot be empty"
It only happens when trying to upload a file larger than 2mb
Can't figure out why can't upload larger files.
P.S.: I can upload a big file via Postman. The problem is when trying to upload via a browser.
What I'm doing wrong?
Thanks in advance
Well, the problem was in php.ini at the max upload file size config.
Just changed to a larger number and now it is working!
Thanks anyways!

Error when pass FormData from vue to laravel controller

i'm working on an laravel vuejs spa.
I try to update a post from the admin. I send the form datas on creating a new FromData who are sending with and axios request.
But the controller send me the error:
message: "The given data was invalid."
errors: {name: ["The name field is required."], description: ["The description field is required."]}
Here is the post/edit.vue
<template>
<div class="post-edit">
<form id="form" #submit.prevent="createPost">
<!-- Title -->
<div class="form-group">
<label for="title" class="form-label">Title</label>
<input id="title" v-model="post.title" :title="post.title" type="text"
name="title" class="form-control"
>
</div>
<!-- Category -->
<div class="form-group">
<label for="category" class="form-label">Category</label>
<select id="category" v-model="post.category" :value="post.category" :category="post.category"
name="category" class="form-control"
>
<option disabled :value="post.category">
Choisir une catégorie
</option>
<option v-for="(category) in categories" :key="category.id" :value="post.category">
{{ category.name }}
</option>
</select>
</div>
<div class="post-edit-image">
<img :src="path + post.image" alt="">
</div>
<!-- Image -->
<div class="form-group post-edit-select-image">
<label for="content" class="form-label">Image</label>
<input type="file" name="image" class="form-control" #change="selectedImage">
</div>
<!-- Content -->
<div class="form-group">
<label for="content" class="form-label">Content</label>
<editor
id="content"
v-model="post.content"
api-key="the-api-key"
:init="{
height: 500,
menubar: false,
plugins: [
'advlist autolink lists link image charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table paste code help wordcount'
],
toolbar:
'undo redo | formatselect | bold italic backcolor | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | removeformat | help'
}"
name="content"
:content="post.content"
/>
</div>
<!-- Submit Button -->
<button type="submit" class="btn btn-primary">
Sauvegarder
</button>
</form>
</div>
</template>
<script>
import axios from 'axios'
import { mapGetters } from 'vuex'
import Editor from '#tinymce/tinymce-vue'
export default {
middleware: 'auth',
components: {
'editor': Editor
},
props: ['id'],
data () {
return {
post: {
id: '',
user_id: '',
title: '',
category: '',
image: null,
content: ''
},
path: '/images/post/thumbnail/'
}
},
computed: {
...mapGetters({
user: 'auth/user',
categories: 'categories/categories'
})
},
beforeCreate () {
this.$store.dispatch('categories/fetchCategories')
},
created () {
this.getPostById(this.$route.params.id)
},
methods: {
selectedImage (event) {
this.post.image = event.target.files[0]
},
getPostById (id) {
axios.get('/api/posts/edit/' + id)
.then((response) => {
this.post.id = response.data.id
this.post.user_id = response.data.user_id
this.post.title = response.data.title
this.post.category = response.data.category
this.post.image = response.data.image
this.post.content = response.data.content
})
.catch((error) => {
console.log(error)
})
},
createPost (e) {
this.post.userId = this.user.id
let formData = new FormData(e.target)
let id = this.post.id
formData.append('title', this.post.title)
formData.append('category', this.post.category)
formData.append('image', this.post.image)
formData.append('content', this.post.content)
axios.patch('/api/posts/update/' + id, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
console.log(response)
this.$store.dispatch('posts/fetchPosts')
})
.catch((error) => {
console.log(error)
})
this.$router.push({ name: 'admin' })
}
}
}
</script>
And here the laravel controller PostController#update method
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(PostUpdateRequest $request, $id)
{
$post = Post::findOrFail($id);
$post->update($request->getValidRequest());
return response()->json($request, 200);
}
And the custom validator PostUpdateRequest.php
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|max:250|unique:posts,title',
'category' => 'required',
'image' => 'mimes:jpg,jpeg,png,bmp',
'content' => 'required'
];
}
public function getValidRequest()
{
$image = $this->file('image');
$slug = Str::slug($this->input('title'));
if (isset($image)) {
$imageExt = $image->getClientOriginalExtension();
$currentDate = Carbon::now()->toDateString();
$imageName = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $imageExt;
if (!Storage::disk('public')->exists('post')) {
Storage::disk('public')->makeDirectory('post');
}
if (!Storage::disk('public')->exists('post/thumbnail')) {
Storage::disk('public')->makeDirectory('post/thumbnail');
}
$path = "images/";
$postImage = Image::make($image)->resize(null, 1060, function ($constraint){
$constraint->aspectRatio();
})->save(public_path($path).'post/'.$imageName);
$thumbnail = Image::make($image)->fit(550, 550)
->save(public_path($path).'post/thumbnail/'.$imageName);
}
return [
'user_id' => Auth::user()->getAuthIdentifier(),
'category_id' => $this->input('category'),
'title' => $this->input('title'),
'slug' => $slug,
'content' => $this->input('content'),
'image' => $imageName,
'is_published' => $this->input('is_published') ?? false,
];
}
The api route in laravel
Route::patch('/update/{id}', 'Backend\PostController#update');
I use practically the same things to store a post, and it work's fine, the only difference is here i pass an id for the post to update and i not use the post method but patch for axios and the route (and i try with put, it's the same error).
thank's for your time !
append '_method' field with value 'PATCH' to formData
formData.append('_method', 'PATCH')
and send axios request post request to update data
axios.post('/api/posts/update/' + id, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})

Trying to upload an image using laravel and vuejs

I have my upload html form like this
<div class="album_single_data settings_data">
<div class="album_single_img">
<figure class="thumbnail thumbnail-rounded">
<img class="main-profile" :src="getprofilepicture()" alt="">
</figure>
</div>
<div class="album_single_text">
<div class="album_btn profile_image">
<div class="btn btn-primary">
<input class="settings-file-upload" type="file" #change="updateProfilePic" ref="file" accept="image/*">
<div class="settings-file-icon">
<span class="material-icons">camera_alt</span>
Upload Profile Picture. (Note: Must Be Less Than 2MB)
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<button #click="updateInfo" class="btn btn-primary">Update Profile</button>
</div>
This is the vuejs code that handles the form submit/upload method which means anytime i click on the upload button the image uploads. but the problem is that it does not submit
export default {
name: 'Settings',
components: {
//
},
data() {
return{
form: new Form ({
id: '',
username:'',
email: '',
password: '',
name: '',
bio: '',
twitter_handle: '',
facebook_handle: '',
instagram_handle: '',
backgroundPicture: ''
}),
pic: ({
profilePicture: '',
})
}
},
created(){
axios.get("profile")
.then(({ data })=>(this.form.fill(data)))
.then(()=>(this.pic.data))
;
},
methods: {
getprofilepicture()
{
//default avatar pic if there is no photo of user
let profilePicture = "http://localhost:8000/img/profile/user.png";
//returns the current path of the
if (this.pic.profilePicture) {
if (this.pic.profilePicture.indexOf('base64') != -1) {
profilePicture = this.pic.profilePicture;
} else {
profilePicture = 'http://localhost:8000/img/profile/' + this.pic.profilePicture;
}
return profilePicture;
}
return profilePicture;
//let profilePicture = (this.form.profilePicture.length > 200) ? this.form.profilePicture : "http://localhost:8000/img/profile/"+ this.form.profilePicture ;
//return profilePicture;
},
// getBackgroundPic(){
// let backgroundPicture = "http://localhost:8000/img/profile/background.jpg";
// if(this.form.backgroundPicture){
// if(this.form.backgroundPicture.indexOf('base64') != -1){
// backgroundPicture = this.form.backgroundPicture;
// }else {
// backgroundPicture = 'http://localhost:8000/img/profile/'+ this.form.backgroundPicture;
// }
// return backgroundPicture;
// }
// return backgroundPicture;
// },
updateInfo(){
this.$Progress.start();
this.form.put('profile')
.then(()=> {
this.$Progress.finish();
this.$router.go('/profile')
})
.catch(()=>{
this.$Progress.fail()
})
},
updateProfilePic(e){
let file = e.target.files[0];
//console.log(file);
let reader = new FileReader();
if(file['size'] < 2097152){
reader.onloadend = () => {
//console.log('RESULT', reader.result)
this.pic.profilePicture = reader.result;
}
reader.readAsDataURL(file);
}else{
Toast.fire({
icon: 'error',
title: 'Ooops...',
text: 'The file you are trying to upload is more than 2MB',
})
}
},
updateBackgroundPic(e){
let file = e.target.files[0];
//console.log(file);
let reader = new FileReader();
if(file['size'] < 2097152){
reader.onloadend = () => {
this.form.backgroundPicture = reader.result;
}
reader.readAsDataURL(file);
}else{
Toast.fire({
icon: 'error',
title: 'Ooops...',
text: 'The file you are trying to upload is more than 2MB'
})
}
}
}
}
</script>
Anytime i click on the submit button i have this error message: "Undefined offset: 1", exception: "ErrorException",…}
exception: "ErrorException"
and i really do not know the cause of this error.
Below is the PHP Code that handles the server side part of the upload
public function updateProfile(Request $request)
{
$user = auth('api')->user();
$this->validate($request,[
'username' => 'required|string|max:255|unique:users,username,'.$user->id,
'name' => 'max:255',
'email' => 'required|string|email|max:255|unique:users,email,
'.$user->id,
'password' => 'sometimes|required|min:8'
]);
$currentProfilePicture = $user->profilePicture;
if($request->profilePicture != $currentProfilePicture){
$name = time().'.' . explode('/', explode(':', substr($request->profilePicture, 0, strpos($request->profilePicture, ';')))[1])[1];
Image::make($request->profilePicture)->save(public_path('img/profile/').$name);
$request->merge(['profilePicture' => $name]);
$userPhoto = public_path('img/profile/').$currentProfilePicture;
if(file_exists($userPhoto)){
#unlink($userPhoto);
}
}
$user->update($request->all());
}

Unable to upload a file using Vue.js to Lumen backend?

I have tried to upload a file using vue.js as front end technology and laravel in the back end. I have tried to pass the file object using formData javascript object but the server responds as the value is not passed.
I have tried to log the file using console.log and it appropriately displays the data.
Consider that I have discarded some field names.
Template Code
<template>
<b-container>
<div align="center">
<b-card class="mt-4 mb-4 col-md-8" align="left" style="padding: 0 0;">
<card-header slot="header" />
<b-form>
<div class="row">
<div class="col-6 col-md-6">
<b-button
type="submit"
variant="success"
class="float-right col-md-5"
v-if="!update"
#click="save"
squared
>
<i class="fas fa-save"></i>
Save
</b-button>
</div>
</div>
<hr style="margin-top: 10px;" />
<b-form-group
label-cols="12"
label-cols-lg="3"
label-for="input-2"
label="Remark: "
label-align-sm="right"
label-align="left"
>
<b-form-textarea
id="textarea"
v-model="record.remark"
rows="2"
max-rows="3"
></b-form-textarea>
</b-form-group>
<b-form-group
label-cols="12"
label-cols-lg="3"
label-for="input-2"
label="Remark: "
label-align-sm="right"
label-align="left"
>
<b-form-file
v-model="record.attachement"
:state="Boolean(record.attachement)"
placeholder="Choose a file..."
drop-placeholder="Drop file here..."
></b-form-file>
</b-form-group>
</b-form>
<status-message ref="alert" />
</b-card>
</div>
</b-container>
</template>
Script Code
<script>
import { mapGetters, mapActions } from "vuex";
export default {
props: ["id", "user_id"],
data: () => ({
record: {
remark: "",
attachement: null
}
}),
methods: {
...mapActions([
"addBenefitRequest",
]),
save(evt) {
evt.preventDefault();
this.$validator.validate().then(valid => {
if (valid) {
const Attachement = new FormData();
Attachement.append("file", this.record.attachement);
var object = {
remark: this.remark
};
this.addBenefitRequest(object, Attachement);
}
});
},
},
computed: mapGetters([
"getStatusMessage",
"getBenefitRequest",
])
};
</script>
Store Code
async addBenefitRequest({ commit }, object, Attachement) {
try {
const response = await axios.post(
commonAPI.BENEFIT_BASE_URL + "/benefit-requests",
object,
Attachement,
{
headers: {
"Content-Type": "multipart/form-data"
}
}
);
commit("pushBenefitRequest", response.data);
commit("setStatusMessage", "Record has been added.");
} catch (error) {
return error
},
Controller Code
public function store(Request $request, Request $request2)
{
$this->validate($request, [
'employee_id' => 'required|string',
'requested_date' => 'required|date',
// 'benefit_type_id' => 'required|string|exists:benefit_types,id',
'reason' => 'required|string',
]);
$this->validate($request2, [
'attachement' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
// $success = BenefitRequest::exists($request->employee_id);
// if(!$success)
// return response()->json("Employee doesn't exist", 422);
$id = (string) Str::uuid();
if($request2->attachement)
{
$attachement = $request2->file('attachement')->store('Benefits');
$request->merge(['attachement' => $attachement]);
}
// $request->attachement = $request->file('attachement')->store('Benefits');
$request->merge(['id' => $id]);
BenefitRequest::create($request->all());
return response()->json('Saved', 201);
}
Route
$router->post('',
['uses' => 'BenefitRequestController#store',
'group'=>'Benefit requests',
'parameter'=>'employee_id, requested_date, requested_by, benefit_type_id, reason, remark, status',
'response'=>'<statusCode, statusMessage>'
]);
Here is an example. you can try it
index.vue
`<div id="app">
<div v-if="!image">
<h2>Select an image</h2>
<input type="file" #change="onFileChange">
</div>
<div v-else>
<img :src="image" />
<button #click="removeImage">Remove image</button>
</div>
</div>`
new Vue({
el: '#app',
data: {
image: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function (e) {
this.image = '';
}
}
})

I can not save values using POST method - laravel vue

I'm trying to save the data I send from the Event view. in the storeEvent method of the EventController driver but it gives me error 422 and I can not find the problem so far.
The Event model has a many-to-many relationship with the Categories model, and Event also has a many-to-many relationship with the Coins model, which is why I occupy vue-multiselect since the user can select several categories or several coins for the same event
Event.vue
<template>
<form v-on:submit.prevent="createdEvent" class="form-horizontal">
<div class="form-group row">
<label>Titulo</label>
<input type="text" name="title" maxlength="25" v-model="title">
</div>
<div class="form-group row">
<label>*Cryptodivisas</label>
<multiselect v-model="coinvalue" :options="coins"
:multiple="true" label="name"
track-by="id" placeholder="Seleccione">
</multiselect>
</div>
<div class="form-group row">
<label>*Categoría</label>
<multiselect v-model="categoryvalue" :options="categories"
:multiple="true" label="name"
track-by="id" placeholder="Seleccione">
</multiselect>
</div>
<div class="col-sm-12">
<button class="btn" type="submit">Crear evento</button>
</div>
</form>
<script>
import Multiselect from 'vue-multiselect';
export default {
components: {
Multiselect,
},
props: ['auth'],
data () {
return {
user: {},
title: '',
coins: [],
coinvalue: [],
categories: [],
categoryvalue: [],
}
},
created() {
this.getCoins();
this.getCategories();
},
mounted() {
this.user = JSON.parse(this.auth);
},
methods: {
getCoins(){
let urlCoin = '/dashboard/coins';
axios.get(urlCoin)
.then((response) => {
this.coins = response.data;
})
.catch((err) => {
})
},
getCategories(){
let urlCategories = '/dashboard/categories';
axios.get(urlCategories)
.then((response) => {
this.categories = response.data;
})
.catch((err) => {
})
},
createdEvent(){
let urlEvent = '/dashboard/newEvent';
const eventData = {
'id' : this.user.id,
'title' : this.title,
'coin' : this.coinvalue,
'category' : this.categoryvalue,
}
console.log(eventData);
axios.post(urlEvent, eventData)
.then((response) => {
console.log(ok);
})
.catch((err) => {
console.log(err.response.data);
})
}
</script>
storeEvent (EventController)
public function storeEvent(Request $request)
{
$this->validate($request, [
'title' => 'required|max:25',
'coin' => 'required',
'category' => 'required',
]);
$userAuth = Auth::user()->id;
$userEvent = $request->id;
if($userAuth === $userEvent){
$event = new Event;
$event->user_id = $userEvent;
$event->title = $request->title;
if($event->save()){
$event->coins()->attach($request->coin);
$event->categories()->attach($request->category);
return response()->json([
'status' => 'Muy bien!',
'msg' => 'Tu evento ya fue creado con éxito.',
], 200);
}
else {
return response()->json([
'status' => 'Error!',
'msg' => 'No pudimos crear tu evento.',
], 401);
}
}
}
I think the problem may be when I assign the values to the coin () -> attach () and category () -> attach () section, but I have no idea how to solve it due to my inexperience in the tool.
The system was made entirely in Laravel and it worked without problems, now that it is being updated with Vue it began to give inconveniences.
Any ideas? I occupy Laravel 5,6, Vuejs 2, Axios and Vue-multiselect 2
Try sending form data
Here is the example for you.
var urlEvent = '/dashboard/newEvent';
var form_data = new FormData();
form_data.append('id',this.user.id);
form_data.append('title',this.title);
for(let coin of this.coinvalue)
form_data.append('coin[]', coin);
for(let category of this.categoryvalue)
form_data.append('category[]', category);
axios(urlEvent,{
method: "post",
data: form_data
})
.then(res => {
console.log(ok);
})
.catch(err => {
console.log(err.response.data);
});
If this stills gives you a 422 status code (Unprocessable entities). Then try returning $request in you controller. And check what data are actually send to the controller and what your validation is.
422 means validation error so do a console.log or inspect the element on axios call and check that :
'title' : this.title,
'coin' : this.coinvalue,
'category' : this.categoryvalue,
Are not empty, cause right now some data from above is missing since its a 422 validation exception.

Resources