【问题标题】:I can not save values using POST method - laravel vue我无法使用 POST 方法保存值 - laravel vue
【发布时间】:2018-10-06 09:25:23
【问题描述】:

我正在尝试保存从事件视图发送的数据。在 EventController 驱动程序的 storeEvent 方法中,但它给了我错误 422,到目前为止我找不到问题。

Event模型和Categories模型是多对多的关系,Event也和Coins模型是多对多的关系,这就是为什么我使用vue-multiselect,因为用户可以选择多个类别或多个硬币用于同一事件

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(事件控制器)

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

我认为问题可能出在我将值分配给 coin () -> attach () 和 category () -> attach () 部分时,但由于我没有经验,我不知道如何解决它工具。

该系统完全在 Laravel 中制作,运行时没有问题,现在它正在使用 Vue 进行更新,它开始带来不便。

有什么想法吗?我占用 Laravel 5,6, Vuejs 2, Axios 和 Vue-multiselect 2

【问题讨论】:

    标签: laravel laravel-5 vue.js vuejs2 axios


    【解决方案1】:

    尝试发送表单数据

    这是给你的例子。

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

    如果这仍然为您提供 422 状态代码(无法处理的实体)。然后尝试在控制器中返回 $request。并检查哪些数据实际发送到控制器以及您的验证是什么。

    【讨论】:

    • 太好了,现在我的问题是如何将类别数据和硬币保存在与事件相关的表格中,我在$ event-&gt; coins () -&gt; attach ($ request-&gt; coin); $ event-&gt; categories () -&gt; attach ($ request-&gt; category); 中有这段代码
    • 如果您使用的是一对多关系。您可以制作循环来保存它。 foreach($request-&gt;coin as $coin)
    • 我在事件到硬币和事件到类别之间使用多对多关系
    • 你确定。 $request-&gt;coin 是 ids,并保存在硬币表中。 ?
    • 我解决了问题,数据保存在事件表和中间表中,现在的问题是当信息保存时它返回一个响应错误Uncaught (in promise) TypeError: Can not read property 'data' of undefined
    【解决方案2】:

    422 表示验证错误,因此请执行 console.log 或检查 axios 调用上的元素并检查:

     'title'         : this.title,
     'coin'          : this.coinvalue,
     'category'      : this.categoryvalue,
    

    不为空,因为上面的一些数据现在丢失了,因为它是 422 验证异常。

    【讨论】:

    • axios的数据发送好,问题出在controller方法
    猜你喜欢
    • 2018-10-31
    • 2021-07-02
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2022-01-19
    • 2021-12-22
    相关资源
    最近更新 更多