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?
Related
I have a Controller method like this:
use Validator;
public function insert(Request $request)
{
$data = Validator::make(request()->all(),[
'title' => 'required',
'name' => 'required|alpha_num',
'activation' => 'nullable',
'cachable' => 'nullable'
])->validated();
$wallet = new Wallet();
$wallet->title = $data['title'];
$wallet->name = $data['name'];
if (!empty($data['activation'])) {
$wallet->is_active = 1;
} else {
$wallet->is_active = 0;
}
if (!empty($data['cachable'])) {
$wallet->is_cachable = 1;
} else {
$wallet->is_cachable = 0;
}
$wallet->save();
return redirect(url('admin/wallets/index'));
}
And then I tried showing errors like this:
#error("name")
<div class="alert alert-danger">{{$message}}</div>
#enderror
But the problem is, it does not print any error when I fill the form incorrectly.
So how to fix this and show errors properly?
Here is the form itself, however it submits data to the DB correctly:
<form action="{{ route('insertWallet') }}" method="POST" enctype="multipart/form-data">
#csrf
<label for="title" class="control-label">Title</label>
<br>
<input type="text" id="title-shop" name="title" class="form-control" value="" autofocus>
#error("title")
<div class="alert alert-danger">{{$message}}</div>
#enderror
<label for="title" class="control-label">Name</label>
<br>
<input type="text" id="title-shop" name="name" class="form-control" value="" autofocus>
#error("name")
<div class="alert alert-danger">{{$message}}</div>
#enderror
<input class="form-check-input" type="checkbox" name="cachable" value="cashable" id="cacheStatus">
<label class="form-check-label" for="cacheStatus">
With Cash
</label>
<input class="form-check-input" type="checkbox" name="activaton" value="active" id="activationStatus">
<label class="form-check-label" for="activationStatus">
Be Active
</label>
<button class="btn btn-success">Submit</button>
</form>
check the official documentation here
add the following code
if($data->fails()){
return redirect(url('admin/wallets/index'))->withErrors($data)->withInput();
}
And after that save your data in your database
You are not returning any errors, you are just redirecting back to the view without any data.
Your fix would be to have your validator as this:
$data = Validator::validate(request()->all(),[
'title' => 'required',
'name' => 'required|alpha_num',
'activation' => 'nullable',
'cachable' => 'nullable'
]);
See that I have changed Validator::make to Validator::validate. As the documentation states:
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.
If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned.
So, if your validation passes, it will save all the validated data into $data, as you did with ->validated() (but you don't have to write it here), and if it fails, it will automatically throw an Exception, in this case ValidationException, so Laravel will automatically handle it and redirect back with to the same URL and with the errors. So it now should work...
This is the Validator::validate source code and this is the validate source code for the validator validate method.
I have this function for registering users which is pretty much the default one but i added a token to be sent to an email so the user can activate the account, otherwise the user cant log in. So i tried to add a resend function so if the first time the email is not send they can resend manually, but that causes the 419 error Page Expired.
Register function
protected function create(array $data)
{
$user = Account::create([
'login' => $data['login'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'verifyToken'=> Str::random(40),
'active' => (env('CONFIRM_EMAIL', true)) ? 0 : 1
]);
$thisUser = Account::findOrFail($user->id);
$this->sendEmail($thisUser);
return $user;
}
This is the function for resend
protected function resend(Request $request)
{
$user = Account::where('email', $request->input('email'))->first();
$user->verifyToken = Str::random(40);
$user->save();
$this->sendEmail($user);
return $user;
}
And i call it with this form
<form action=" {!! route('resendEmail') !!}" method="POST">
<fieldset class="youplay-input">
<input id="email" type="email" class="#error('email') is-invalid #enderror" placeholder="E-
mail" name="email" value="{{ old('email') }}" required autocomplete="email">
</fieldset>
<button class="btn btn-default db" type="submit" value="Submit">
Resend Verification Link
</button>
</form>
I have discussed this with a guy but we couldnt find a good solution: How to make resend email link function in Laravel
You are missing your csrf token in the form. After <form> tag add #csrf.
Example:
<form method="POST" action="/profile">
#csrf
</form>
https://laravel.com/docs/7.x/csrf
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();
}
I'm trying to pass 2 dates from one view to another, in my controller, but I get the following error:
Argument 2 passed to App\Http\Controllers\GuestController::reservationToGuest() must be an instance of Illuminate\Http\Request, none given
This is my first view (the view having the date):
<form action="{{ route('create_guest') }}">
{{ csrf_field() }}
<input type="hidden" value="2016-08-26" name="dateOne">
<input type="hidden" value="2016-08-28" name="dateTwo">
<button class="btn btn-block btn-success">Proceed To Check In</button>
</form>
(dateOne and dateTwo are the dates which I want in the second view)
routes.php
Route::get('/guest_page/create/{idreservation?}',[
'uses' => 'GuestController#reservationToGuest',
'as' => 'create_guest'
]);
reservationToGuest in GuestController
public function reservationToGuest($idreservation = null, Request $request){
if($idreservation === null){
return view('guest_page_create', ['idreservation' => 0, 'page_title' => 'Guest Check In', 'check_in_date' => $request['dateOne']]);
} else{ //else clause works just fine and the dates from the database are inserted into the view
$details = DB::table('reservation')
->where('idreservation', $idreservation)
->get();
return view('guest_page_create', ['idreservation' => $idreservation, 'details' => $details, 'page_title' => 'Guest Check In']);
}
}
And in view 'guest_page_create'
<label for="datemask">Check In Date</label>
<input type="date" class="form-control" id="datemask" name="datemask" value="{{ $check_in_date }}">
You shouldn't pass optional parameters before required ones. Try this:
public function reservationToGuest(Request $request, $idreservation = null)
{
// ...
}
I'm trying to change the status of a database record with just a button click so far I have this:
view
<td>
<a class="btn btn-small btn-warning" href="{{ URL::to('brands/'.$value->BrandID.'/archive') }}">Archive </a>
</td>
controller
public function archive($id)
{
$rules= array ('BrandName' =>'required | max:20',);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails())
{
return Redirect::to('brands.view')
->withErrors($validator);
} else {
DB::table('tbl_brands')->where('BrandID' , $id)
->update(
array
(
'Status' => 'Archived'
));
Session::flash('message','Successfully Archived!');
return Redirect::to('brandsview');
}
}
and the route
Route::put('brands/{id}/archive', array('as' => 'Brandarch', 'uses'=>'BrandsController#archive'));
and my error what method exception. I scrolled down a bit and saw that in the errors, the http request is 'get' which I know should be 'put' any ideas on how to properly execute this?
You will need to change your hyperlink to a submit form in a form with hidden field with name _method, only this way you can control HTTP method used.
For example:
<form action="{{ URL::to('brands/'.$value->BrandID.'/archive') }}" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" value="Archive">
</form>