2016-11-12 157 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/*', 
    ]; 
}