Route [RemindersController#postRemind] not defined error in Laravel4 - php

I was implementing Laravel's password reminded function but hitting this error:
Route [RemindersController#postRemind] not defined.
I am using Laravel 4 and absolutely new to Laravel.I used
php artisan auth:reminders-controller
to create RemindersController.
<?php
class RemindersController extends Controller {
public function getRemind()
{
return View::make('password_remind');
}
public function postRemind()
{
Password::remind(Input::only('email'), function($message)
{
$message->subject('Password Reminder');
});
}
public function getReset($token = null)
{
if (is_null($token)) App::abort(404);
return View::make('password.reset')->with('token', $token);
}
public function postReset()
{
$credentials = Input::only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function($user, $password)
{
$user->password = Hash::make($password);
$user->save();
});
switch ($response)
{
case Password::INVALID_PASSWORD:
case Password::INVALID_TOKEN:
case Password::INVALID_USER:
return Redirect::back()->with('error', Lang::get($response));
case Password::PASSWORD_RESET:
return Redirect::to('/');
}
}
}
I created view password_remind.blade.php which is shown below :
#extends('layouts.default_layout')
#section('content')
<div class="row" style="min-height: 376px">
<div class="col-sm-4">
</div>
<div class="col-sm-4">
</div>
<div class="col-sm-4" style="padding-top: 70px;">
<div class="login">
<form action="{{action('RemindersController#postRemind')}}" method="POST">
<input type="email" name="email" placeholder="Email">
<input type="submit" value="Send">
</form>
</div>
</div>
</div>
#stop
In root I added Route::get('forgotPassword', 'RemindersController#getRemind');
The url http://localhost/laravel_work/public/forgotPassword gives
Route [RemindersController#postRemind] not defined
error.
Where am I wrong ? I cannot find the mistake.Pls Help Me :(*

Welp, if you look at your form you have action="{{action('RemindersController#postRemind')}}"
But according to you, the only route you added was RemindersController#getRemind
I'm assuming you want just the get to quickly check the view right now, but maybe the action() is actually eagerly looking for that non-existent route.
Is your app dying when you post the form or when you get the view? Either way defining the route for the post like you did with the get should fix it.

Related

Php laravel - page only shows white after login

My registration page works well. As I registered a new account, it then redirects me to the "home" page. However, when I tried to login, it redirects me to a blank white page. I tried to check the route, the action="login" on the form, at the controller, it all corrects. I tried different way of writing the code such as Auth::Attempt as well as auth()->attempt(). I compared it with the register page that I've created. It should be fine. I really have no idea where I did wrong. Please help. I need to complete a project by next week tuesday. I'm in a very tight schedule right now.
Route code
Route::get('/', function () {
return view('home');
});
Route::get('/record', function () {
return view('record');
});
Route::get('/profile', function () {
return view('profile');
});
Route::get('register', [RegisterController::class, 'create'])->middleware('guest');
Route::post('register', [RegisterController::class, 'store'])->middleware('guest');
Route::get('login', [SessionsController::class, 'create'])->middleware('guest');
Route::post('session', [SessionsController::class, 'store'])->middleware('guest');
Route::post('logout', [SessionsController::class, 'destroy'])->middleware('auth');
Controller page
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
class SessionsController extends Controller
{
public function create()
{
return view('sessions.create');
}
public function store()
{
$attributes = request()->validate([
'email' => 'required|email',
'password' => 'required'
]);
if (Auth::Attempt($attributes)) {
return redirect('/')->with('success', 'Your account has been created.');
}
}
public function destroy()
{
auth()->logout();
redirect('/')->with('success', 'Goodbye');
}
}
Home page
<x-layout>
<div id="sidebar" class="bg-gray-100 border border-black border-opacity-5 w-96 py-8 px-8 mt-16 text-white">
<div class="relative flex lg:inline-flex items-center border border-gray-400 rounded-l px-3 py-3 text-white">
<form method="GET" action="/">
<input type="text" name="search" placeholder="Search Staff" class="bg-transparent placeholder-gray font-semibold text-sm" value="{{ request('search') }}">
</form>
</div>
<div class="relative lg:inline-flex bg-gray-100 rounded-xl">
<x-category-dropdown />
</div>
</div>
</x-layout>
The likely cause of this is that your Auth::attempt() is failing. You have no fallback/default response if it fails:
// redirect ONLY IF authentication succeeds
if (Auth::Attempt($attributes)) {
return redirect('/')->with('success', 'Your account has been created.');
}
// we get here if authentication fails, but do nothing
Add in a fallback redirect for instances where authentication fails:
if (Auth::Attempt($attributes)) {
return redirect('/')->with('success', 'Your account has been created.');
}
return redirect('/')->with('errors', 'Authentication failed.');

Laravel Error to inicialice ValidationFactory

I'm making my login system, through the LoginController controller, which in turn calls a request called loginRequest [I still have to update some names to Pascal]
My request only has two rules that username and password are required.
Then in a function getCredentials() I capture the username of this and validate that it is an email or not, this to give the user the option to log in both ways.
To identify if the user is actually an email, create a method 'isMail' in which I establish $factory with the content validated through an alias set to Validacion\Factory , ValidationFactory, but when executing the submit button it throws me the error :
Target [Illuminate\contracts\Validation\Factory] is not instantiable.
Could you help me?
template [login.blade.php]:
#extends('components\header')
<section class="vh-100">
<div class="container-fluid h-custom">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-4">
<img src="{{ URL::asset('img/logo.png') }}"
class="img-fluid" height="500">
</div>
<div class="col-md-8 col-lg-6 col-xl-4 offset-xl-1">
<form action="{{route('samein.login')}}" method="POST">
#csrf
<!-- Email input -->
<div class="form-outline mb-4">
<input type="text" name="username" class="form-control form-control-lg"
placeholder="Usuario" />
<label class="form-label" for="form3Example3">Usuario</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="password" class="form-control form-control-lg"
placeholder="Contraseña" />
<label class="form-label" for="form3Example4">Contraseña</label>
</div>
<div class="text-rigth text-lg-start mt-4 pt-2">
<button type="submit" class="btn btn-primary btn-lg"
style="padding-left: 2.5rem; padding-right: 2.5rem;">Iniciar Sesión</button>
</div>
</form>
</div>
</div>
</div>
</section>
controller[LoginController.login]
<?php
namespace App\Http\Controllers;
use App\Http\Requests\loginrequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Queue\RedisQueue;
class LoginController extends Controller
{
public function index(){
return view('login');
}
public function login( loginrequest $request ){
$credentiales = $request->getCredentials();
if( Auth::validate($credentiales) ){
return redirect()->to('login')->withErrors('auth.failed');
}
$user = Auth::getProvider()->retrieveByCredentials($credentiales);
Auth::login($user);
return $this->authenticated($request,$user);
}
public function authenticated (Request $request,$user){
return redirect('accountModule.indexusers');
}
}
and my Request[loginrequst.php]
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\contracts\Validation\Factory as ValidationFactory;
class loginrequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
public function getCredentials(){
$username = $this->get('username');
if( $this->isMail($username) ){
return['email'=> $username,
'password' => $this->get('password')
];
}
return $this->only('username','password');
}
public function isMail($value){
$factory = $this->container->make(ValidationFactory::class);
return !$factory->make(['username'=>$value],['username'=>'email'])->fails();
}
}
I was reading your problem and I found interesting the way you plan to check if the email is there or not.
I know it doesn't answer your question but you could try the following:
In your Request:
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
In your controller:
public function login( loginrequest $request ){
$field = filter_var($request->input('username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('username')]);
//validate credentials
if (!Auth::validate($request->only($field, 'password'))) {
return redirect()->to('login')->withErrors('auth.failed');
}
//create a session
$user = Auth::getProvider()->retrieveByCredentials($request->only($field, 'password'));
Auth::login($user);
return redirect()->to('/');
}
don't forget to configure your web.php file, so that the routes work for you. I hope I've helped.

Too few arguments to function, 0 passed and exactly 1 expected in Laravel

I have a project in Laravel-5.8.
'actionURL' => route('appraisal.appraisal_goals.goal_adjustment_self_review', ['id'=>$employeeId]),
From the Notification actionUrl, I passed ['id'=>$employeeId] into:
public function goal_adjustment_self_review($id)
{
$goals = AppraisalGoal::where('employee_id', $id)->whereNull('deleted_at')->get();
return view('appraisal.appraisal_goals.goal_adjustment_self_review')->with(['goals' => $goals]);
}
Then I have this edit controller functions generated from goal_adjustment_self_review($id)
public function goal_adjustment_edit($id)
{
$userCompany = Auth::user()->company_id;
$userId = Auth::user()->employee_id;
$goal = AppraisalGoal::findOrFail($id);
return view('appraisal.appraisal_goals.goal_adjustment_edit')
->with('goal', $goal);
}
public function goal_adjustment_update(UpdateAppraisalGoalAdjustmentRequest $request, $id)
{
DB::beginTransaction();
try {
$goal = AppraisalGoal::findOrFail($id);
$goal->goal_type_id = $request->goal_type_id;
$goal->weighted_score = $request->weighted_score;
$goal->save();
DB::commit();
Session::flash('success', 'Goal Setting Weight is updated successfully');
return redirect()->route('appraisal.appraisal_goals.goal_adjustment_self_review');
} catch (Exception $exception) {
Log::error($exception);
DB::rollback();
Session::flash('error', 'Action failed! Please try again');
return redirect()->route('appraisal.appraisal_goals.goal_adjustment_self_review');
}
}
view: goal_adjustment_edit
<form action="{{route('appraisal.appraisal_goals.goal_adjustment_update', ['id'=>$goal->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Weight(%):<span style="color:red;">*</span></label> <input type="hidden" id="goal_weight_balance" value="0" disabled>
<input id="total_weighted_score" type="text" name="weighted_score" value="{{old('weighted_score',$goal->weighted_score)}}" placeholder="Enter weighted score here" class="form-control" max="120" onkeyup="checkScore(this.value)">
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
route:
Route::group(['prefix' => 'appraisal', 'as' => 'appraisal.', 'namespace' => 'Appraisal', 'middleware' => ['auth']], function () {
Route::get('appraisal_goals/goal_adjustment_self_review/{id?}', 'AppraisalGoalsController#goal_adjustment_self_review')->name('appraisal_goals.goal_adjustment_self_review');
Route::get('appraisal_goals/goal_adjustment_edit/{id?}', 'AppraisalGoalsController#goal_adjustment_edit')->name('appraisal_goals.goal_adjustment_edit');
Route::put('appraisal_goals/goal_adjustment_update/{id?}', 'AppraisalGoalsController#goal_adjustment_update')->name('appraisal_goals.goal_adjustment_update');
});
When I submitted the update form above, I got this error:
[2020-12-18 20:10:46] production.ERROR: Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::goal_adjustment_self_review(),
0 passed and exactly 1 expected
For this line:
public function goal_adjustment_self_review($id)
How do I get this resolved?
The error is very clear, you are not passing a parameter to the method. The method is called by the routing engine, which means you are not passing a route parameter that you should.
Your controller method goal_appraisal_update() includes this line (twice for some reason):
return redirect()->route('appraisal.appraisal_goals.goal_adjustment_self_review');
Where is the parameter?
What you should be doing is using route model binding so your controller method looks like this:
public function goal_adjustment_self_review($employee)
{
$goals = $employee->appraisal_goals;
return view('appraisal.appraisal_goals.goal_adjustment_self_review')
->with('goals', $goals);
}
public function goal_adjustment_edit(AppraisalGoal $goal)
{
return view('appraisal.appraisal_goals.goal_adjustment_edit')
->with('goal', $goal);
}
public function goal_adjustment_update(UpdateAppraisalGoalAdjustmentRequest $request, AppraisalGoal $goal)
{
try {
$goal->update($request->only('goal_type_id', 'weighted_score'));
Session::flash('success', 'Goal Setting Weight is updated successfully');
} catch (\Exception $exception) {
Log::error($exception);
Session::flash('error', 'Action failed! Please try again');
}
return redirect()
->route('appraisal.appraisal_goals.goal_adjustment_self_review', $goal);
}
And then routes can be defined like so:
Route::group(['prefix' => 'appraisal', 'as' => 'appraisal.', 'namespace' => 'Appraisal', 'middleware' => ['auth']], function () {
Route::get('appraisal_goals/goal_adjustment_self_review/{employee}', 'AppraisalGoalsController#goal_adjustment_self_review')
->name('appraisal_goals.goal_adjustment_self_review');
Route::get('appraisal_goals/goal_adjustment_edit/{goal}', 'AppraisalGoalsController#goal_adjustment_edit')
->name('appraisal_goals.goal_adjustment_edit');
Route::put('appraisal_goals/goal_adjustment_update/{goal}', 'AppraisalGoalsController#goal_adjustment_update')
->name('appraisal_goals.goal_adjustment_update');
});
Note the route parameters match the name of the method parameters. When type is declared in the method signature, magic happens.

view or redirect in laravel not working for another method

i'm new in Laravel 5 framework. I make a form. In the form, I create one button to search inventory codes and then fill the text input in the form. The Controllers are work well. But, when I try return view('cari'), the browser doesn't show up anything. These is my codes:
in Controller:
public function search(){
echo "212";
return view('cari');
}
The index method in my controller works well.
public function checkAction()
{
if(Input::get('submit')) {
$this->create();
} else if(Input::get('cari')) {
$this->search();
}
}
Then, I try another way use return redirect('cari'); in my controller with no display anything.
If I edit my post in routes.php and directly call myController#search it does display the cari.blade.php. But, I want from the search form trigger to browse inventory items. Could you give me some clues?.
This is my permintaan.blade.php which i created a button to checkAction():
<form class="form-horizontal" role="form" method="POST" action="{{ url('/permintaan') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">Kode Inventaris</label>
<div class="col-md-6">
<input type="text" class="form-control" name="kodeInventaris" value="{{ old('kdInventaris') }}">
</div>
<button type="submit" class="btn btn-primary" name="cari" value="cari">
Cari
</button>
</div>
....
</form>
These is my create and store functions:
public function create(Request $request)
{
$data = $request->except('_token');
$validator = $this->validator($data);
if ($validator->fails())
{
$this->throwValidationException(
$request, $validator
);
}
$this->store($data);
$request->find($request);
return redirect()->back()->with('message', 'Permintaan berhasil diinput');
}
public function store(array $data){
Permintaan::create([
'kdInventaris' => $data['kodeInventaris'],
'namaInventaris' => $data['namaInventaris'],
'jenis' => $data['optInventaris'],
'jumlah' => $data['jumlah'],
'spesifikasi' => $data['spesifikasi'],
'keterangan' => $data['keterangan'],
]);
}
when redirect. It works, but got a blank page again. and replace with echo.
It works, but has this message and got a successful redirect:
"HTTP/1.0 302 Found Cache-Control: no-cache Date: Mon, 01 Jun 2015 16:04:33 GMT Location: http://localhost:8000/permintaan Redirecting to http://localhost:8000/permintaan."
I wonder with my return redirect()->back()->with('message', 'Permintaan berhasil diinput');
You're doing the operation and not returning any view in your controller
You can do it by
public function checkAction()
{
if(Input::get('submit')) {
$this->create();
return view('cari')->with('message', 'Succesfully created');
} else if(Input::get('cari')) {
$this->search();
return view('cari')->with('message', 'Search Done');
}
}
Note :
I dont know any of your view name so i am using the same name cari you can replace it with any view that you have.

token mismatch execption - laravel auth

I have following routes
Route::controller('users', 'UsersController');
Controllers
class UsersController extends BaseController {
protected $layout = "layouts.login";
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth', array('only'=>array('getDashboard')));
}
public function getRegister() {
$this->layout->content = View::make('users.register');
}
public function logout() {
Auth::logout();
return Redirect::to('users/login')
->with('message', 'Good Bye')
->withInput();
}
public function getLogin() {
$this->layout->content = View::make('users.login');
}
public function postSignin() {
if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password'),'role'=>'admin'))) {
return Redirect::to('mix/dashboard')->with('message', 'You are now logged in!');
}
else {
return Redirect::to('users/login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
public function postCreate() {
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->passes()) {
// validation has passed, save user in DB
$user = new User;
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('users/login')->with('message', 'Thanks for registering!');
} else {
// validation has failed, display error messages
return Redirect::to('users/register')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}
}
}
view
<div class="login-body">
<h2>SIGN IN</h2>
<form method="post" action="{{Request::root()}}/users/Signin">
<div class="control-group">
<div class="email controls">
{{ Form::text('email', null, array('class'=>'input-block-level', 'placeholder'=>'Email Address', 'data-rule-required'=>'true' ,'data-rule-email'=>'true')) }}
</div>
</div>
<div class="control-group">
<div class="pw controls">
{{ Form::password('password', array('class'=>'input-block-level', 'placeholder'=>'Password','data-rule-required'=>'true')) }}
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
</div>
</div>
<div class="submit">
<div class="remember">
<input type="checkbox" name="remember" class='icheck-me' data-skin="square" data-color="blue" id="remember"> <label for="remember">Remember me</label>
</div>
{{ Form::submit('Login', array('class'=>'btn btn-primary'))}}
{{ Form::close() }}
<div class="forget">
<span>Forgot password?</span>
</div>
</div>
Whenever i try to login it shows tokenmismatch exception error and shows following lines of filter.php
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
I have been clueless past three days...
worst is that this error automatically came , it was working fine earlier .. i did not make any changes at all !
It was client side issue
I just deleted cookies and then it start working.
You probably add the crsf filter in the /users/Signin route. You have several options:
Fistly, you can remove the crsf filter from the route.
Second, you should add the csrf token to your form input (after the <form ...> line)
{{ Form::token(); }}
Or you can change your Form declaration using the Form macro with also include the csrf token.
{{ Form::open(array('url' => 'users/Signin' ) ); }}
I hope it helps you.
Avoid having csrf on your GET routes since they don't have a token and will throw TokenMismatchException. With that said you could look at this snippet of code you could add in your controller to avoid these exceptions:
`class UserController extends BaseController {
/**
* Instantiate a new UserController instance.
*/
public function __construct()
{
$this->beforeFilter('auth', array('except' => 'getLogin'));
$this->beforeFilter('csrf', array('on' => 'post'));
$this->afterFilter('log', array('only' =>
array('fooAction', 'barAction')));
}
}
`
As you can see the CSRF filter is only being applied on the POST method and the auth one is only being applied on the getLogin controller method.

Categories