2016-11-12 151 views
0

我想要使用vue-resource this.$http.post請求發佈ajax請求。它工作得很好,如果我通過所有驗證規則,但如果失敗,我想得到一些驗證。到目前爲止,如果我不填寫某些輸入字段,我會收到500錯誤。我很難調試錯誤,因爲它沒有出現在網絡選項卡上。Laravel使用vue js驗證

這裏是我到目前爲止

//my modal component 
<script> 
export default { 
    props: ['show'], 

    data() { 
     return { 
      input: { 
       id: '', 
       name: '', 
       address: '', 
       email: '' 
      }, 
      errorInputs: {} 
     } 
    }, 

    methods: { 
     createStudent() { 
      this.$http.post('/students', this.$data.input) 
       .then((response) => { 
       alert('added new row!) 
      }, (response) => { 
       console.log(response.data); 
      }); 
     } 
     } 
    } 
</script> 

// my controller 

public function store(Request $request) { 
    $validator = $this->validate($request,[ 
     'id' => 'required', 
     'name' => 'required|unique:students', 
     'email' => 'required|unique:students|email', 
     'address' => 'required', 
    ]); 

    if($validator->passes()){ 
     Student::create($request->all()); 

     return response()->json([], 201); 
    } 

    $errors = json_decode($validator->errors()); 

    return response()->json([ 
     'success' => false, 
     'message' => $errors 
    ],422); 
} 

任何幫助和參考,將不勝感激完成。我使用laravel 5.3和VUE JS 2

+0

也許你有你的網絡選項卡上啓用過濾器?檢查您的標籤上是否標記了「all」(或至少「xhr」)。這肯定會有幫助。你也可以在'storage/log/laravel.log'中檢查日誌。 – Skysplit

+0

是的,我意識到在發佈我的問題後,抱歉。你能幫我如何通過laravel驗證到vue js組件嗎?我在這一點上陷入困​​境。 – ishadif

+0

然後有什麼問題?到目前爲止,您正朝着良好的方向前進,據我所見 – Skysplit

回答

2

$this->validate()回報你一起驗證錯誤422錯誤響應,所以你應該then()秒回調得到這些錯誤(比如你現在做的)。你VUE成分的身體應該是這樣的:

{ 
    data() { 
     // ... 
    }, 
    createStudent() { 
     this.$http 
      .post('/students', this.input) 
      .then(this.handleSuccess, this.handleError) 
    }, 
    handleSuccess(res) { 
     alert('student created') 
    }, 
    handleError(res) { 
     if (res.status === 422) { 
      this.errorInputs = res.body 
     } else { 
      alert('Unkown error!') 
     } 
    } 
} 

記住v-model="input.fieldName"屬性添加到您的輸入。

+0

謝謝,但我仍然得到500以某種方式。我想我的laravel代碼有問題。我稍後會回覆 – ishadif

+0

顯然我已經改變了'handler.php'上的渲染函數在這個代碼返回之前拋出異常'return parent :: render($ request,$ exception);'。這就是爲什麼我不斷收到500錯誤。在vue側的驗證現在可以正常工作 – ishadif

+0

@ishadif Geat聽到了!希望我的回答至少可以幫助你一點點:) – Skysplit

0

請記住包括您的會話令牌以及您的帖子,除非您正在禁用該路由的csrf令牌。

由於Laravel 5.1,你可以在你的verifytoken中間件禁用此

<?php namespace App\Http\Middleware; 

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as ... 

class VerifyCsrfToken extends ... { 
    protected $except = [ 
    'payment/*', 
    ]; 
}