简体   繁体   English

如何在Web Service上为移动应用程序使用Laravel 5.4验证程序

[英]How to use Laravel 5.4 validator at web service for mobile application

I have a problem with Laravel 5.4 validator which is I'm trying to validate data comes from a mobile application but when validator fails it redirect to the home page. 我在Laravel 5.4验证器上遇到问题,这是我正在尝试验证数据是否来自移动应用程序,但是当验证器失败时,它将重定向到主页。 I need to prevent this redirect and return a json response with validation errors messages 我需要防止这种重定向并返回带有验证错误消息的json响应
Here's my route.php code 这是我的route.php代码

Route::group(['middleware' => 'web'], function() {
   Route::post('/userSignUp', [
       'uses' => 'UserController@userSignUp', 
       'as'   => 'userSingUp'
   ]);
});

And this is my controller code 这是我的控制器代码

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class UserController extends Controller
{

    public function userSignUp(Request $request){
        $fullName   = $request->input('fullName');
        $email      = $request->input('email');
        $phone      = $request->input('phone');
        $password   = $request->input('password');
        $userType   = $request->input('userType');
        $profilePic = $request->input('profilePic');


        $validator = $this->validate($request, [
                    'fullName' => 'required|max:255',
                    'email'    => 'required|email',
                    'phone'    => 'required'
                ]);

        if ($validator->fails()) {    
            return response()->json($validator->messages(), 200);
        }
    }
} 

So can anyone help me solving this issue I need to use a laravel 5.4 validator in a web service for a mobile application so I need to prevent the validator redirecting as it does in the above code it redirecting to home page when validation is failed 所以任何人都可以帮助我解决这个问题,我需要在移动应用程序的Web服务中使用laravel 5.4验证程序,因此我需要防止验证程序重定向,就像上面代码中所做的那样,当验证失败时它将重定向到主页
thanks in advance 提前致谢

if the validation fails when you call $this->validate($request,$rules) laravel will throw an exception and a failed validation response will be sent back by this method define in Illuminate\\Foundation\\Validation\\ValidatesRequests : 如果在调用$this->validate($request,$rules)时验证失败$this->validate($request,$rules) laravel将抛出异常,并且失败的验证响应将通过Illuminate\\Foundation\\Validation\\ValidatesRequests定义的此方法发送回:

/**
 * Create the response for when a request fails validation.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  array  $errors
 * @return \Symfony\Component\HttpFoundation\Response
 */
protected function buildFailedValidationResponse(Request $request, array $errors)
{
    if ($request->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return redirect()->to($this->getRedirectUrl())
                    ->withInput($request->input())
                    ->withErrors($errors, $this->errorBag());
}

So it seems that Laravel does handle that by checking $request->expectsJson() so you need to specify the Accept header in you request to JSON, then a JSON formatted response with code 422 will be returned. 因此,看来Laravel确实通过检查$request->expectsJson()来处理此问题,因此您需要在对JSON的请求中指定Accept标头,然后将返回代码422的JSON格式的响应。

return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->withCallback($request->input('callback'));

from the official doc https://laravel.com/docs/5.4/responses#json-responses 来自官方文档https://laravel.com/docs/5.4/responses#json-responses

And maybe try to make your validation in your model directly 也许尝试直接在模型中进行验证

class User extends Eloquent
{
   private $rules = array(
      'fullName' => 'required|max:255',
      'email'    => 'required|email',
      'phone'    => 'required|numeric'
   );


  public function validate($data)
  {
    // make a new validator object
    $v = Validator::make($data, $this->rules);
    // return the result
    return $v->passes();
  }
}

and in your controller you can make 在您的控制器中,您可以

$new = Input::all();
$u = new User();
if ($b->validate($new))
{

}
else
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM