Laravel and upload image more than 2MB - laravel

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!

Related

RTK createEntityAdapter not getting relational data in list after save user in database

i have a list of users which getting data from database by using RTK createEntityAdapter.
API function code for getting list of users
public function index(){
$roles = Role::all();
$all_roles = [];
foreach ($roles as $key => $role) {
$obj_role = new \stdClass();
$obj_role->id = $role->id;
$obj_role->name = $role->title;
array_push($all_roles,$obj_role);
}
return response()->json([
'users' => User::with('roles')->paginate(10),
'roles' => $all_roles
]);
}
In the above code getting users and roles in response & showing list in react app by using RTK createEntityAdapter
userSlice.js
import { createSlice,createEntityAdapter} from "#reduxjs/toolkit";
import { HTTP_STATUS } from "../../src/constants";
import { fetchUsers, deleteUsers, saveUser } from "services/userService";
const userAdapter = createEntityAdapter({
selectId: (user) => user.id,
})
const userSlice = createSlice({
name:'user',
initialState: userAdapter.getInitialState(
{ loading: false,
page: 1,
total_pages: null,
status: null,
message: null,
roles: []
} ),
reducers:{
pageByNumber: (state,{payload}) => {
state.page = payload.page
},
nextPage: (state, {payload}) => {
state.page = state.page++
},
previousPage: (state, {payload}) => {
state.page = state.page--
},
clear: (state) => {
state.status = null,
state.message = null
}
},
extraReducers: {
[fetchUsers.pending]: (state) => {
state.loading = true,
state.status = HTTP_STATUS.PENDING
},
[fetchUsers.fulfilled]: (state, {payload}) => {
state.loading = false,
state.page = payload.users.current_page,
state.total_pages = Math.ceil(payload.users.total/payload.users.per_page),
userAdapter.setAll(state, payload.users.data),
state.status = HTTP_STATUS.FULFILLED,
state.roles = payload.roles
},
[fetchUsers.rejected]: (state, {error}) => {
state.loading = false,
state.status = HTTP_STATUS.REJECTED,
state.message = error.message
},
[deleteUsers.pending]: (state) => {
state.loading = true,
state.status = HTTP_STATUS.PENDING
},
[deleteUsers.fulfilled]: (state, { payload }) => {
state.loading = false,
userAdapter.removeOne(state, payload.id)
},
[deleteUsers.rejected]: (state) => {
state.loading = false
},
[saveUser.pending]: (state) => {
state.loading = true,
state.status = HTTP_STATUS.PENDING
},
[saveUser.fulfilled]: (state, { payload }) => {
state.loading = false,
state.status = HTTP_STATUS.FULFILLED
if(!payload.errors){
userAdapter.addOne(state, payload.id),
state.message = payload.message
}
},
[saveUser.rejected]: (state,{error}) => {
state.loading = false,
state.status = HTTP_STATUS.REJECTED,
state.message = error.message
}
},
});
export const userSelectors = userAdapter.getSelectors(
(state) => state.user,
)
export const {pageByNumber, nextPage, previousPage,clear} = userSlice.actions
export default userSlice.reducer
user/index.js
const roles = useSelector(state => state.user.roles);
const allUsers = useSelector(userSelectors.selectAll);
useEffect(() => {
dispatch(
fetchUsers(currentPage))
.then(unwrapResult)
.then((obj) => console.log(obj))
.catch((obj) => console.log({objErr: obj}))
}, [dispatch])
//listing HTML
{
allUsers.map((ls,index) => (
<tr key={ls.id}>
<td>{ls.id}</td>
<td>{ls.name}</td>
<td>{ls.email}</td>
<td>
{ls.status =="ACTIVE" ? <Badge color="success" pill>Active</Badge>:<Badge color="danger" pill>Inactive</Badge>}</td>
<td>
{ls.roles.map((role) => (
role.title+" "
))}
</td>
<td><Moment fromNow ago>{ls.created_at}</Moment> </td>
<td>
<Button variant="warning" size="sm" onClick={handleShow} >Edit</Button>{' '}
<Button
onClick={e =>
window.confirm("Are you sure you wish to delete this user?") &&
deleteUser(ls.id)
}
variant="danger"
size="sm">Delete</Button>
</td>
</tr>
))
}
create.js
import {Modal, Button, Form,Dropdown} from "react-bootstrap";
import propTypes from "prop-types";
import React, {useState} from "react";
import Multiselect from 'multiselect-react-dropdown';
import { saveUser } from 'services/userService';
import {useDispatch,useSelector} from 'react-redux';
import { unwrapResult } from '#reduxjs/toolkit';
import Notify from "components/Common/Notify";
function Create({handleClose,show,roles}) {
const [selectedRoles, setSelectedRoles] = useState([]);
const dispatch = useDispatch();
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [errors, setErrors] = useState([]);
function onSelectRoles(selectedList, selectedItem) {
selectedRoles.push(selectedItem.id)
}
function onRemoveRole(selectedList, removedItem) {
var index = selectedRoles.indexOf(removedItem.id)
selectedRoles.splice(index, 1);
}
const message = useSelector(state => state.user.message);
const status = useSelector(state => state.user.status);
function onSubmit(e){
e.preventDefault();
let data ={
name:name,
email:email,
password:password,
roles:selectedRoles,
}
dispatch(
saveUser(data))
.then(unwrapResult)
.then((obj) => {
if(obj.errors){
setErrors(obj.errors);
}else{
setErrors([]);
handleClose();
}
}
)
.catch((obj) => {
console.log({objErr: obj})
})
}
return (
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>New User</Modal.Title>
</Modal.Header>
<Modal.Body>
{status && message && (
<Notify status={status} message={message}/>
)}
<Form onSubmit={onSubmit} >
<Form.Group className="mb-3">
<Form.Label>Name</Form.Label>
<Form.Control className={errors['name'] ? "is-invalid" : ""} type="text" onChange={e => setName(e.target.value) } placeholder="Enter Name" />
{errors['name'] ?
<Form.Text className="text-danger">
{errors['name']}
</Form.Text>
:''
}
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control className={errors['email'] ? "is-invalid" : ""} type="email" onChange={e => setEmail(e.target.value) } placeholder="Enter email" />
{errors['email'] ?
<Form.Text className="text-danger">
{errors['email']}
</Form.Text>
:''
}
</Form.Group>
<Form.Group>
<Form.Label>Select Role</Form.Label>
<Multiselect
options={roles}
// selectedValues={selectedValue}
onSelect={onSelectRoles}
onRemove={onRemoveRole}
displayValue="name"
className={errors['roles'] ? "is-invalid" : ""}
/>
{errors['roles'] ?
<Form.Text className="text-danger">
{errors['roles']}
</Form.Text>
:''
}
</Form.Group>
<Form.Group>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control className={errors['password'] ? "is-invalid" : ""} type="password" onChange={e => setPassword(e.target.value)} placeholder="Password" />
{errors['password'] ?
<Form.Text className="text-danger">
{errors['password']}
</Form.Text>
:''
}
</Form.Group>
<Button variant="success" size="sm" type="submit">
Create
</Button>
</Form>
</Modal.Body>
</Modal>
);
}
Create.prototype= {
handleClose: propTypes.func.isRequired,
show: propTypes.bool.isRequired,
roles: propTypes.array.isRequired
}
export default Create;
when i add new user by using saveUser createEntityAdapter, not getting relational data "role" & getting error
i found the problem in my code, actually createEntityAdpter addone works looks like below
Adapter.addOne(state, payload.data);
i was passing only id in addOne function, as below
[saveUser.fulfilled]: (state, { payload }) => {
state.loading = false,
state.status = HTTP_STATUS.FULFILLED
if(!payload.errors){
userAdapter.addOne(state, payload.id), //wrong approach
state.message = payload.message
}
it should be pass full object in addOne function of createEntityAdapter
[saveUser.fulfilled]: (state, { payload }) => {
state.loading = false,
state.status = HTTP_STATUS.FULFILLED
if(!payload.errors){
userAdapter.addOne(state, payload.user),
state.message = payload.message
}
Now, this will work fine. now i am getting all relational data too in response.

Looking for a way to translate(i18n) laravels form validation rules inside a Vue form

So I have build an form in laravel with Vue with some validation rules and this works, when there's an error it will show me an message but I also have an locales switcher present which also works for the text in the form but not for the validation output, so there are always in English. I am using the i18n
plugin to translate the text.
Is there a way to make the validation rules i18n ready?
registerController.php
protected function validator(array $data)
{
$customMessages = [
'name' => 'some custom message can go here...',
];
$validator = Validator::make($data, [
'name' => ['required', 'min:2', 'string', 'max:100'],
'email' => ['required', 'email', 'string', 'max:255', 'unique:users'],
'password' => [
'required'
'min:10',
'regex:/[a-z]/', // must contain at least one lowercase letter
'regex:/[A-Z]/', // must contain at least one uppercase letter
'regex:/[0-9]/', // must contain at least one digit
'regex:/[#$!%*#?&]/', // must contain a special character
],
], $customMessages);
return $validator;
}
componentForm.vue
<template>
<form #submit.prevent="formSubmit">
<el-input type="text" name="name" v-model="fields.name"
label="Name" :error="errors.name"/>
<el-input type="email" name="email" v-model="fields.email"
label="E-mailaddress" :error="errors.email"/>
<el-input type="password" name="password" v-model="fields.password"
label="Password" :error="errors.password"/>
<button type="submit" class="btn btn--primary btn--xl btn--block">
{{ $t("auth.register") }}
</button>
</form>
</template>
<script>
import espressoLocale from '../../Components/Contextual/Locale';
import espressoCard from '../../Components/UI/Card';
import elInput from '../../Components/Forms/Input';
export default {
components: {
elInput,
},
data() {
return {
fields:{
name: "",
email: "",
password: "",
},
errors: {
name: null,
email: null,
password: null,
},
}
},
methods: {
resetFields () {
this.fields.name = "";
this.fields.email = "";
this.fields.password = "";
},
formSubmit (e) {
e.preventDefault();
this.errors = {};
axios.get('/sanctum/csrf-cookie').then(response => {
axios({
method: 'post',
url: '/api/register',
data: {
name: this.fields.firstname,
email: this.fields.email,
password: this.fields.password,
},
validateStatus: (status) => {
return true;
}
}).then(response => {
if (response.data.success) {
} else {
this.errors = response.data.errors || {};
}
}).catch(function (error) { });
});
}
},
}
</script>
You should write :error="$t(errors.name)" in your components as you write {{ $t("auth.register") }} to show translated text about register. I assume that you get i18n locale structured object in your errors response, something like this:
errors: {
name: 'errors.name',
...
}

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

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

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

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