I can not save values via POST - laravel vue

2

I'm trying to save the data I send from the Event view. I went to 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 also Event 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 coin 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>
 </template>
 <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

    
asked by Felipe 25.04.2018 в 20:06
source

1 answer

2

The problem is that when trying to send the values by post with axios , the value of coinvalue and categoryvalue are objects selected, but what is needed are only the id to use in the controller,

To achieve this, before sending the data, you can filter them in order to obtain a new array with only the id's , for this you can use map in the following way.

createdEvent(){
  let urlEvent = '/dashboard/newEvent';
  let idcoin = this.coinvalue.map(e=> e.id); 
  let idcategory = this.categoryvalue.map(e=> e.id);
  const eventData = {
      'id' : this.user.id,
      'title' : this.title,
      'coin' : idcoin ,
      'category': idcategory 
 }
 axios.post(urlEvent, eventData) ...
    
answered by 26.04.2018 / 01:16
source