Laravel's AuthController doesn't validate my fields properly - php

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',
]);

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'
] );

Laravel - prepopulate input data after validation failed

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();
}

Laravel 5.1 Trying to post data to controller but geting MethodNotAllowedHttpException error

Im trying to POST data to my controller but I'm getting a
MethodNotAllowedHttpException in RouteCollection.php line 219:
error message, here are my files.
my route file
<?php
Route::get('/', function () {
return view('welcome');
});
// Authentication routes
Route::get('auth/login', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
// Registration routes
Route::get('register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
Route::controllers(['password' => 'Auth\PasswordController',]);
Route::get('/home', 'HomeController#index');
// Using A Route Closure
Route::get('profile', ['middleware' => 'auth', function() {
// Only authenticated users may enter...
Route::auth();
}]);
// practicing using forms for sending data to the DB & populating form fields with DB data
Route::get('profile', 'ProfileController#index');
Route::post('profile/update', 'ProfileController#updateProfile');
profile.blade.php
<form method="POST" action="/profile/update/">
<div class="form-group hidden">
<input type="hidden" name="id" value="<?php echo $users[0]->id;?>">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input name="_method" type="hidden" value="PATCH">
</div>
<div class="form-group">
<label for="email"><b>Name:</b></label>
<input type="text" name="name" placeholder="Please enter your email here" class="form-control"/>
</div>
<div class="form-group">
<label for="email"><b>Email:</b></label>
<input type="text" name="email" placeholder="Please enter your email here" class="form-control"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default"> Submit </button>
</div>
</form>
& my ProfileController.php
<?php
namespace App\Http\Controllers;
use Auth;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ProfileController extends Controller
{
/**
* Update user profile & make backend push to DB
**/
public function index()
{
if(Auth::check()) {
// connecting to the DB and accessing
$users = User::all();
//var_dump($users);
return view('profile', compact('users'));
}
return view('auth/login');
}
public function updateProfile(Requests $request) {
return $request->all();
}
}
not sure what the issue is. Thanks for all the help everyone
A couple of issues that we managed to address here:
Over-use of HTTP Verbs
At your view, you have: <form method="POST" but also <input name="_method" type="hidden" value="PATCH"> which may conflict between a POST and a PATCH. Since your routes.php only declares POST, let's remove the patch definition.
Routing Mistake
Still at your view, your action points to action="/profile/update/" while your route is defined as Route::post('profile/update'), notice the extra / at the end in your form. That slash should not be there.
Controllers Request
You have a here: use App\Http\Requests; is probably incorrect because that's a folder within Laravel, not a class. Let's remove that and keep use Illuminate\Http\Request; for now. In the near future, you'll be learning how to create your own Form Requests and you'll probably want a UpdateProfileRequest.php.

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 >

Categories