验证请求时Laravel中的REST API [英] REST API in Laravel when validating the request

查看:56
本文介绍了验证请求时Laravel中的REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试如何使用Laravel构建RESTful API,并且目前正在创建新用户.这只是一个测试,当尝试使用Laravel中的验证来验证请求时,我得到了一些结果.结果如下:

I'm currently trying out on how to build a RESTful API with Laravel and I'm currently in the process of creating a new user. This is just a test and I'm getting some result when trying to validate the request using validation in Laravel; here is the result:

我一直在尝试通过以下代码创建一个新的

I've been trying to create a new one by this code:

public function store()
{

    $validation = Validator::make(Request::all(),[ 
        'username' => 'required|unique:users, username',
        'password' => 'required',
    ]);

    if($validation->fails()){


    } else{
            $createUser = User::create([
                'username' => Request::get('username'),
                'password' => Hash::make(Request::get('password')) 
            ]);
    }
}

但是我不知道如何在验证中返回错误.但是,当我尝试使用 validation->fails() 执行 if 时,它一直为我提供如图所示的 HTML.有没有办法以JSON格式进行验证?

but then I don't know how to return the error in validation. But it keeps on giving me that HTML as showed in the image when I was trying to do the if with validation->fails(). Is there a way to get the validation in JSON format?

推荐答案

这些代码对您有所帮助,为我工作.

$response = array('response' => '', 'success'=>false);
$validator = Validator::make($request->all(), $rules);
    if ($validator->fails()) {
        $response['response'] = $validator->messages();
    }else{
//process the request
}
return $response;

这篇关于验证请求时Laravel中的REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆