REST API in Laravel when validating the request

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

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?


You should probably return errors (which is an instance of IlluminateSupportMessageBag ) and encode that. A MessageBag instance allows you to convert it directly to its JSON representation.

$errors = $validation->errors();

return $errors->toJson();

Now not to toot my own horn but I've recently developed a RESTful API package for Laravel which does all of this for you and all you need to do is throw a simple exception. See my dingo/api package and the Wiki on returning errors. Basically, instead of returning the errors you would throw an exception.

throw new DingoApiExceptionStoreResourceFailedException('Could not create a new user.', $validation->errors());

It would be represented by the following JSON.

{
    "message": "Could not create a new user.",
    "errors": {
        "username": ["The username is already in use."]
    }
}

这些代码将帮助你,为我工作。

$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 provides out of the box a validation method that you can call from your Controller.

if you check the Laravel Controller abstract class you will find it uses a trait called ValidatesRequests

   abstract class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

So you can use a method $this->validate(Request $request, array $rules); as you long as your controller class extends the Controller

the full method declaration is

public function validate(Request $request, array $rules, array $messages = [], array $customAttributes = [])
    {
        $validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);

        if ($validator->fails()) {
            $this->formatValidationErrors($validator);
        }
    }

If The $validator fails, the method will throw an error depending on the request type, if it is ajax (in this case you should include in the request headers ( Accept application/json ) it will return a JSON response containing the validation errors.

链接地址: http://www.djcxy.com/p/8548.html

上一篇: 使用bash shell脚本时遇到问题,尝试使用cURL POST变量JSON数据

下一篇: 验证请求时,Laravel中的REST API