如何在Laravel 5.1中强制FormRequest返回json?在Laravel 5.1 中,如果你想要强制 FormRequest 返回JSON 响应,可以通过重写 failedValidation 方法来实现。这个方法会在请求验证失败时被调用。 以下是一个示例代码,展示了如何在自定义的 FormRequest 类中强制返回 JSON 响应: ...
1 php artisan make:request TestRequest 该类继承 FormRequest类 父类FormRequest中的failedValidation()方法用来处理验证失败,我们需要重写父类方法,实现自己得返回。 1 2 3 4 5 6 7 8 publicfunctionfailedValidation(Validation$validator) { throw(newHttpResponseException(response->json([ 'status_code'=>'50...
记录Laravel 定义API 统一返回JSON响应和错误格式
public function render($request, Exception $exception) { return parent::render($request, $exception); } protected function unauthenticated($request, AuthenticationException $exception) { if($request->expectsJson()){ $response=response()->json([ 'status'=>3, 'msg' => $exception->getMessage(),...
use Illuminate\Http\Exceptions\HttpResponseException; class TestRequest extends FormRequest { /** * 控制访问权限 */ public function authorize() { //注意,默认是false,改成true return true; } /** * 验证规则 */ public function rules()
此时的状态是200,如果需要更改可以再response()->json()的第二个参数传递 <?phpnamespaceApp\Http\Requests;useIlluminate\Foundation\Http\FormRequest;useIlluminate\Http\Exceptions\HttpResponseException;classBaseRequestsextendsFormRequest{/** * 验证失败处理 ...
你猜对了,Form Request就实现了这个Illuminate\Contracts\Validation\ValidatesWhenResolved接口: <?phpnamespaceIlluminate\Foundation\Http;useIlluminate\Http\Request;useIlluminate\Http\Response;useIlluminate\Http\JsonResponse;useIlluminate\Routing\Redirector;useIlluminate\Container\Container;useIlluminate\Contracts\Validati...
php artisanmake:request ProjectValidate 1. 2.定义验证规则。rules 方法是定义验证规则,而 messages 方法则是定义返回的错误信息,该方法也可以省略掉,这样提示的信息就是英文而不是图一或图二看到的中文了。 namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; ...
phpnamespace App\Http\Requests;use Illuminate\Contracts\Validation\Validator;use Illuminate\Foundation\Http\FormRequest;use Illuminate\Http\Exceptions\HttpResponseException;abstract classAPIRequestextendsFormRequest{/*** Determine if user authorized to make this request * @return bool */publicfunction...
Determine if the current request probably expects a JSON response. from InteractsWithContentTypes bool wantsJson() Determine if the current request is asking for JSON. from InteractsWithContentTypes bool accepts(string|array $contentTypes) Determines whether the current requests accepts a given ...