Skip to content

Instantly share code, notes, and snippets.

@moradi-morteza
Last active December 30, 2019 13:46
Show Gist options
  • Save moradi-morteza/6f33d6560c782fc4ea52f791b24085d9 to your computer and use it in GitHub Desktop.
Save moradi-morteza/6f33d6560c782fc4ea52f791b24085d9 to your computer and use it in GitHub Desktop.
[validation] #LaravelT
//VALIDATION
// 1-post data to controller method
// inside controller :
public function store(Request $request){
// $validator = $request->validate([
// 'name' => 'required',
// 'age' => 'required',
// 'email' => 'required',
// ]);
// $this->validate($request, [
// 'name' => 'required',
// 'age' => 'required',
// 'email' => 'required',
// ]);
// commented code just check validate and do not show error , send response code 302
$validator = Validator::make($request->all(), [
'name' => 'required',
'age' => 'required',
]);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
}
//------------------------------html--------------------
// for show error in html:
@if ($errors->any())
<ul>
@foreach ($errors->all() as $error)
<li><span style="color: red">{{ $error }}</span></li>
@endforeach
</ul>
@endif
<form action="/store" method="post">
{{ csrf_field() }}
<input name="name" placeholder="name">
<input name="age" placeholder="age">
<input name="email" placeholder="email">
<button type="submit">Send</button>
</form>
//----------------------------api----------------------------
// if you post data from client like android
public function store(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'required',
'age' => 'required',
'email' => 'required|unique:users,email',
]);
if ($validator->fails()) {
return response($validator->errors(), 403);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment