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.
Related
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.
I am trying to allow a user to update their information after they have submitted a form, but did not check a certain box. Everything is within the same page and I am controlling the different modals by returning a message, which triggers a script to open the different modals.
For some reason, I can't seem to pass the ID or email through to the next step. Can anyone help with this?
Whenever, I try, I get the following error:
Undefined variable: leads
Any idea?
Thanks!!!
Files:
web.php
index.blade.php
LeadsController.php
Leads.php
Web.php
Route::post('/', [
'uses' => 'LeadsController#store',
'as' => 'leads.store'
]);
Route::patch('/{email}', [
'uses' => 'LeadsController#update',
'as' => 'leads.update'
]);
Index.blade.php
<html>
<div id="contact" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form id="form" class="form" action="/" method="post" accept-charset="utf-8">
{{ csrf_field() }}
<input type="email" name="email" value="{{ old('email') }}">
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#if(session()->has('message'))
<div id="sign_up" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form method="post" action="{{ route('leads.update', $leads->email) }}">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#endif
</body>
</html>
LeadsController.php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput($request->all);
} else {
try {
$leads = new Leads;
$leads->email = $request->email;
$leads->newsletter = $request->newsletter;
$leads->save();
if($request->newsletter == ''){
return redirect()->back()->with('message','sign up')->withInput($request->all)->with($leads->email, $request->get('email'));
}
if($request->newsletter == 'true'){
return redirect()->back()->with('success','success');
}
} catch (Exception $e) {
return response()->json(
[
'status' => false,
'error' => base64_encode($e->getMessage()),
],
Status::HTTP_INTERNAL_SERVER_ERROR
);
}
}
}
public function update($email)
{
$leads = Leads::find($email);
$leads->newsletter = $input('newsletter');
$leads->save();
return redirect()->back()->with('success','success');
}
Leads.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Leads extends Model
{
protected $table = 'my_renamed_table';
public $timestamps = false;
protected $fillable = ['email', 'newsletter'];
}
Thanks for all of your help and your questions! You helped push me in the right direction.
Here is how I solved it:
I had to correct myself in how I pushed the $email through to the view:
LeadsController
return redirect()
->back()
->with('message','sign up')
->withInput($request->all)
->with('email', $request->get('email'));
Notice how I'm sending the email through as 'email' here.
Then, I pushed the email through the view in the 2nd form like this:
index
<form method="post" action="{{ route('leads.update', session('email')) }}">
Then, finally, in order to capture the email again, use it to find the lead that I wanted, I had to drastically change the update:
public function update($email)
{
DB::table('my_renamed_table')
->where('email', $email)
->update(['newsletter' => Input::get('newsletter')]);
return redirect()->back()->with('success','success');
}
Thanks again!
I have a number of php files in my project:
admin.blade.php: this files contains the admin form.
When called it show the following error:
MethodNotAllowedHttpException in RouteCollection.php line 201
<h2>Please Log In To Manage</h2>
<form id="form1" name="form1" method="post" action="<?=URL::to('/admin')?>">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
User Name:<br />
<input name="username" type="text" id="username" size="40" />
<br /><br />
Password:<br />
<input name="password" type="password" id="password" size="40" />
<br />
<br />
<br />
<input type="submit" name="button" id="button" value="Log In" />
</form>
In route.php, this call is made:
Route::get('/admin',array('uses'=>'student#admin'));
This is the function in student.php
public function admin()
{
return View::make('student.admin');
$validator = Validator::make($data = Input::all() , User::rules());
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
else
{
$check = 0;
$check = DB::table('admin')->get();
$username = Input::get('username');
$password = Input::get('password');
if (Auth::attempt(['username' => $username, 'password' => $password]))
{
return Redirect::intended('/');
}
return Redirect::back()->withInput()->withErrors('That username/password combo does not exist.');
}
}
I don't know much about creating an admin area, I am just trying to create it.
This is how I do it.
Routes.php
Route::get('/admin', 'UsersController#getAdminLogin');
Route::get('/admin/dashboard', 'UsersController#dashboard');
Route::post('/admin', 'UsersController#postAdminLogin');
admin_login.blade.php
{!! Form::open(['url' => '/admin']) !!}
<div class="form-group">
{!! Form::label('email', 'Email Id:') !!}
{!! Form::text('email', null, ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Password') !!}
{!! Form::password('password', ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::submit('Login', ['class' => 'btn btn-primary btn-block']) !!}
</div>
{!! Form::close() !!}
dashboard.blade.php
<h4 class="text-center">
Welcome {{ Auth::user()->full_name }}
</h4>
UsersController.php
/**
* Display the admin login form if not logged in,
* else redirect him/her to the admin dashboard.
*
*/
public function getAdminLogin()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return redirect('/admin/dashboard');
}
return view('admin_login');
}
/**
* Process the login form submitted, check for the
* admin credentials in the users table. If match found,
* redirect him/her to the admin dashboard, else, display
* the error message.
*
*/
public function postAdminLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email|exists:users,email,role,admin',
'password' => 'required'
]);
$credentials = $request->only( 'email', 'password' );
if(Auth::attempt($credentials))
{
return redirect('/admin/dashboard');
}
else
{
// Your logic of invalid credentials.
return 'Invalid Credentials';
}
}
/**
* Display the dashboard to the admin if logged in, else,
* redirect him/her to the admin login form.
*
*/
public function dashboard()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return view('admin.dashboard');
}
return redirect('/admin');
}
Your Code:
In routes.php, you have only 1 route, i.e.,
Route::get('/admin',array('uses'=>'student#admin'));
And there is no declaration of post method, hence, the MethodNotAllowedHttpException
Also, in your controller, you are returning the view first and then processing the form which is not going to work at all. You first need to process the form and then return the view.
public function admin(){
// Won't work as you are already returning the view
// before processing the admin form.
return \View::make(students.admin);
// ...
}
As #Sulthan has suggested, you should use Form Facade. You can check out this video on Laracasts about what Form Facade is and how you should use it.
You're using post method in the form but you're having get method in the routes.
So, Change the method to post in your routes
Note :
I recommend you to make use of the default form opening of Laravel like the below given which is always the best practise
{!! Form::open(array('url' => 'foo/bar')) !!}
{!! Form::close() !!}
Tips :
Read more on here and try to debug such things by comparing the methods and routes.
Form facade is not included in laravel 5 by default. You shall install it by
composer require "illuminate/html":"5.0.*"
and updating in the app.php.
I have written a blog which gives a breif about this installation.
In Routes web.php
Your code is
Route::get('/admin',array('uses'=>'student#admin'));
which is wrong.
Actually submitting data in POST method its array of data so you need to route through post instead of get.
so correct code is
Route::post('/admin',array('uses'=>'student#admin'));
Follow this tutorial form Laracast it might helpful,
https://laracasts.com/series/laravel-from-scratch-2017/episodes/16
In routes.php, replace Route::get by Route::post.
You have no post route for your form data posting , use route match function for both http verb (get & post). use this
Route::match(['get', 'post'], '/admin', 'student#admin');
Also you need to change your admin method,
public function admin(Request $request){
if($request->isMethod('get')){
return \View::make('student.admin');
} else {
// your validation logic
}
}
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.
I just downloaded and started a new project with the latest Laravel 4.2. When trying to submit a form I get the following error : BadMethodCallException Method [store] does not exist
Here are my files : controller - admin/AdminController
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index() {
if (Input::has('Login')) {
$rules = array(
'email' => 'required',
'password' => 'required|min:3',
'email' => 'required|email|unique:users'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('admin\AdminController')->withErrors($validator);
} else {
// redirect
Session::flash('message', 'Successfully created user!');
return Redirect::to('admin\AdminController');
}
}
$data['title'] = ADMIN;
return View::make('admin.index', $data);
}
}
View page - admin/index.blade.php
<div class="container">
{{ Form::open(array('url' => ADMIN,'id' => 'login')) }}
<div id="icdev-login-wrap">
<div class="raw align-center logoadmin">{{ HTML::image('images/logo.png') }}</div>
<div id="icdev-login">
<h3>Welcome, Please Login</h3>
<div class="mar2_bttm input-group-lg"><input type="text" class="form-control loginput" placeholder="Email" name="email"></div>
<div class="mar2_bttm input-group-lg"><input type="password" class="form-control loginput" placeholder="Password" name="password"></div>
<div ><input type="submit" class="btn btn-default btn-lg btn-block cus-log-in" value="Login" /></div>
<div class="row align-center forgotfix">
<input type="hidden" name="Login" value="1">
</div>
</div>
<div>
</div>
</div>
{{ Form::close() }}
</div>
The error message tells you what the problem is: the method called store() doesn’t exist. Add it to your controller:
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index()
{
// leave code as is
}
public function store()
{
// this is your NEW store method
// put logic here to save the record to the database
}
}
A couple of points:
Use camel-casing for name spaces (i.e. namespace admin should be namespace Admin)
Read the Laravel documentation on resource controllers: http://laravel.com/docs/controllers#resource-controllers
You can also automatically generate resource controllers with an Artisan command. Run $ php artisan make:controller ItemController, replacing ItemController with the name of the controller, i.e. ArticleController or UserController.