Repository navigation
Expand file tree
/
Copy pathValidatesRequests.php
More file actions
102 lines (91 loc) · 2.68 KB
/
Copy pathValidatesRequests.php
File metadata and controls
102 lines (91 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace Laravel\Lumen\Routing;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Validator;
use Illuminate\Http\Exception\HttpResponseException;
trait ValidatesRequests
{
/**
* Validate the given request with the given rules.
*
* @param \Illuminate\Http\Request $request
* @param array $rules
* @param array $messages
* @param array $customAttributes
* @return void
*/
public function validate(Request $request, array $rules, array $messages = [], array $customAttributes = [])
{
$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);
if ($validator->fails()) {
$this->throwValidationException($request, $validator);
}
}
/**
* Throw the failed validation exception.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*/
protected function throwValidationException(Request $request, $validator)
{
throw new HttpResponseException($this->buildFailedValidationResponse(
$request, $this->formatValidationErrors($validator)
));
}
/**
* Create the response for when a request fails validation.
*
* @param \Illuminate\Http\Request $request
* @param array $errors
* @return \Illuminate\Http\Response
*/
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
}
/**
* Format the validation errors to be returned.
*
* @param \Illuminate\Validation\Validator $validator
* @return array
*/
protected function formatValidationErrors(Validator $validator)
{
return $validator->errors()->getMessages();
}
/**
* Get the URL we should redirect to.
*
* @return string
*/
protected function getRedirectUrl()
{
return app('session')->previousUrl();
}
/**
* Get a validation factory instance.
*
* @return \Illuminate\Contracts\Validation\Factory
*/
protected function getValidationFactory()
{
return app('validator');
}
/**
* Get the key to be used for the view error bag.
*
* @return string
*/
protected function errorBag()
{
return 'default';
}
}