Last active
December 30, 2019 13:46
-
-
Save moradi-morteza/6f33d6560c782fc4ea52f791b24085d9 to your computer and use it in GitHub Desktop.
[validation] #LaravelT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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