Laravel - prepopulate input data after validation failed - php

I used 5.4 and I've an index action in convert controller which shows the form and then have another action calculate in the convert controller. So the form has from-currency, amount, to-currency input and all of them are required.
Here's the validation I've for calculate action:
$this->validate(request(), [
'from_currency' => 'required|min:3|max:3|alpha',
'to_currency' => 'required|min:3|max:3|alpha',
'amount' => 'required|numeric',
]);
If the validation failed I want when showing the errors and the form it will prepopulate the input already.
Is there like a function I can use for Request ? I know how to get the domain/path inside blade like Request::root() and I also tried Request::input('from_currency) in the view but not work.
I even tried to set the view data like 'from_currency' => request('from_currency') and it's blank. Any idea?

When you are validating your form your request if it fail you can redirect to the same page with all the input which was submited
$validator = Validator::make($request->all(), [
'from_currency' => 'required|min:3|max:3|alpha',
'to_currency' => 'required|min:3|max:3|alpha',
'amount' => 'required|numeric',
]);
if ($validator->fails()) {
return redirect('index')
->withErrors($validator)
->withInput();
}
and in your blade view you can show the old value by ussing the old helper like this
<input type="text" name="from_currency" value="{{ old('from_currency') }}">
<input type="text" name="to_currency" value="{{ old('to_currency') }}">
<input type="text" name="amount" value="{{ old('amount') }}">

Try this
In your blade file, make sure your inputs have this:
<input type="text" ... value="{{ old('from_currency') }}" ... >.
Then in your controller...
if($validation->fails()) {
return redirect()->back()->withInput();
}

You can also user Validate instead of Validator::make.
eg
$this->validate($request, [
'question' => "required|min:10|max:100",
'answer' => "required|min:20|max:300",
'rank' => "required|numeric|gt:0|lt:100",
]);
Then in your form use
<input type="text" class="form-control" id="question" name="question" value="{{ old('question') }}">
This will automatically redirect back with input if the validator fails.
This way, you DO NOT have to include
if($validation->fails()) {
return redirect()->back()->withInput();
}

Related

MethodNotAllowedHttpException error when doing validation in laravel

The following is my blade :
<form action="{{route('ans1.eval')}}" method="post">
<br>
<input type="radio" name="evaluate" class="evaluate" value=10> 1
<input type="radio" name="evaluate" class="evaluate" value=15> 1.5
<input type="radio" name="evaluate" class="evaluate" value=20> 2
<input type="radio" name="evaluate" class="evaluate" value=25> 2.5
<input type="radio" name="evaluate" class="evaluate" value=30> 3
<button type="submit" class="btn btn-primary" align="right">Evaluate Answer</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
The following is my route :
Route::post('/evaluateans', [
'uses' => 'AnswerController#postEvaluateAns',
'as' => 'ans1.eval',
'middleware' => 'auth'
]);
The following is my validation :
public function postEvaluateAns(Request $request)
{
$this->validate($request, [
'evaluate' => 'required'
]);
}
The following is the error when no evaluation is selected :
MethodNotAllowedHttpException in RouteCollection.php line 218
From the laravel docs on validation
If the validation rules pass, your code will keep executing normally;
however, if validation fails, an exception will be thrown and the
proper error response will automatically be sent back to the user. In
the case of a traditional HTTP request, a redirect response will be
generated.
When your validation fails it redirects back with a GET method (a redirection uses the GET method) but if you show the form from a route that is not a GET one it throws this error.
So you have to show the form with a GET route.
As alternative you can manually create your validator so you can choose the redirect GET route in case of failed validation, e.g.:
public function postEvaluateAns(Request $request)
{
$validator = Validator::make($request->all(), [
'evaluate' => 'required'
]);
if ($validator->fails()) {
return redirect('failed_validation_GET_route')
->withErrors($validator)
->withInput();
}
return redirect()->route('success_GET_route')
->with('status', 'Success!');
}

How to insert data to database with Laravel

I'm trying to insert my data to database from form.
My URL to create the data is web.com/siswa/create
But when I click submit system show error MethodNotAllowedHttpException.
How I can fix it? Is there anything wrong with my code?
Here is my form:
<form action="{{ url('siswa') }}" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">NISN</label>
<input type="text" class="form-control" name="nisn" id="nisn" placeholder="NISN"></div>
<div class="form-group">
<label for="exampleInputEmail1">Nama Siswa</label>
<input type="text" class="form-control" name="nama_siswa" id="nama_siswa" placeholder="Nama Siswa"> </div>
<button type="submit" class="btn btn-success btn-sm font-weight-bold">Submit</button></form>
Controller:
public function tambah()
{
return view('siswa.create');
}
public function store(Request $request)
{
$siswa = new \App\Siswa;
$siswa->nisn = $request->nisn;
$siswa->nama_siswa = $request->nama_siswa;
$siswa->tanggal_lahir = $request->tanggal_lahir;
$siswa->jenis_kelamin = $request->jenis_kelamin;
$siswa->save();
return redirect('siswa');
}
Route:
Route::get('/siswa/create', [
'uses' => 'SiswaController#tambah',
'as' => 'tambah_siswa'
]);
Route::get('/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
]);
change your store function route from get to post
Route::post('/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
]);
Use Csrf protection field in your form for the session timeout error
{{ csrf_field() }}
OR
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
OR if you are using Form builder
{!! Form::token() !!}
In Route please use post instead of get
Route::post('/siswa','SiswaController#store');
and also include {{ csrf_field() }} in form
you are using method="POST" on your form but in on your route you are using Route::get
Use Route::post for your route
In your form you've given POST method, but your router doesn't have any POST handler. So all you have to do is , when you are trying to store data from form to DB you have to post the data, and the router should handle it.
Try this
Route::post('/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
]);
You are using POST method in your form and using GET in route.
try this
Route::post( '/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
] );

PHP: Empty function not working properly

I'm new to laravel and have been going through this code for hours, yet I'm unable to figure out what's really wrong.
I have this form:
<form method="POST" action="{{ action('School1Controller#forgot_password') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" class="form-control" name="matricule" placeholder="Matricule No. or name" >
<input type="email" class="form-control" name="inst_email" placeholder="Password">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
which submits to this method..
public function forgot_password(Request $request){
$this->validate($request, [
'matricule' => 'required',
'inst_email' => 'required'
]);
$input = $request->all();
$student = User::where('matricule', $input['matricule'])->where('inst_email', $input['inst_email'])->get();
// dd($student);
if (empty($student)){
Session::flash('message', 'We have no such user in our records.');
return redirect()->back();
}else{
Session::flash('message', 'Student found. We will reset your password soon.');
return redirect()->back();
}
}
..through this route..
Route::post('/forgot_password', ['as' => 'forgot_password', 'uses' => 'School1Controller#forgot_password']);
When it queries the database, it returns the student properly and I can display it using dd($student). In cases when the student is unavailable, it also displays an empty array. Now the problem is, the message that keeps displaying is that which says student is found regardless whether the $student array holds any student or not. Is there a problem with my empty() function or what?

Laravel 5.1 registration form with new field

I am creating referral system so I have the following routes
// Registration routes...
Route::get('auth/register/{id}', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
and my RegisterUser.php is changed to
public function getRegister($id)
{
return view('auth.register')->withName($id);
}
and my blade looks like
<div class="form-group">
<label class="col-md-4 control-label">Company</label>
<div class="col-md-6">
<input type="text" class="form-control" name="company" value="{{ old('company') }}" readonly disabled>
</div>
</div>
in AuthController I have:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'company' => $data['company'],
'password' => bcrypt($data['password']),
]);
}
and the value="{{ old('company') }}" is causing the problem. When it is like that it works. But I want the value to be value="{{$name}}" given from return view('auth.register')->withName($id); So when I go to route auth/register/something in the input field I have got the 'something' so it is working but I have the error code "Undefined index: company". When I remove the value at all it is working but I need this value. Any suggestions would be helpful.
The Problem of your code is the disabled attribute in the input "company", why ? well a disabled element isn't editable and isn't sent on submit. so Laravel doesn't receive it so you will be able to access via the helpers old.
Remove the disabled attribute and the magic happens.
<input type="text" class="form-control" name="company" value="{{ old('company') }}" readonly >

Laravel's AuthController doesn't validate my fields properly

I am writing an application in Laravel 5.1. According to the documentation I can authenticate and validate my login forms using their AuthController.
The only field I want to validate is a code-input field.
<form method="POST">
<div class="form-group">
<label for="code-input">Code</label>
<input type="text" name="code-input" class="form-control" id="code-input" placeholder="Type your code here">
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<button type="submit" class="btn btn-default">Submit</button>
</form>
However, whenever I set my validation method in the AuthController to check only that field and submit an empty form I get an error that the email field is required and the password field is required. I mean, what?
protected function validator(array $data)
{
return Validator::make($data, [
'code-input' => 'required|max:255'
]);
}
My routes are also working correctly:
Route::get('/', 'Auth\AuthController#getLogin');
Route::post('/', 'Auth\AuthController#postLogin');
Route::get('/logout', 'Auth\AuthController#getLogout');
Does anybody know what is going on?
The validator method is just for creating users (registration). Login is all handled by the AuthenticatesUsers trait postLogin method, which requires email and password.
There are ways to change the "email" requirement easily, but to get rid of both fields and replace with a code, you'll have to write yourself a new postLogin method.
Did you check the postLogin function at AuthenticatesUsers.php? It could have a line of codes something like this which results the validation errors:
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);

Categories