NotFoundHttpException when updating AuthController - laravel

I got a NotFoundHttpException when accessing to POST:http://localhost:8000/auth/register. This error appears when I updating AuthController validator and create methods. With default AuthController there is no error but datas not stored in database
AuthController
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
protected function create(array $data)
{
return User::create([
'lastname' => $data['lastname'],
'firstname' => $data['firstname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:8',
]);
}
}
Routes
Route::post('auth/register', 'Auth\AuthController#postRegister');
User model
namespace App;
use Illuminate\Auth\Authenticatable;
use Jenssegers\Mongodb\Model as Eloquent;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Eloquent implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $collection = 'users_collection';
protected $fillable = ['firstname', 'lastname', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function websites(){
return $this->hasMany('App\Website');
}
}
Route list
http://pastebin.com/Xq24AQLK
Htaccess
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

as I mentioned in my comment out there, and according to your comment mentioning that the user actually gets registered in the database, so to debug the problem, let's take a look at the source code of postRegister method:
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postRegister(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::login($this->create($request->all()));
return redirect($this->redirectPath());
}
As we can see, after the registration, the method redirects to the redirction path returned by redirectPath, let's take a look at its source code as well:
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
if (property_exists($this, 'redirectPath')) {
return $this->redirectPath;
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
As we can see, if the 'redirectTo' attribute is not specified, the method by default redirects to '/home', so you have two possible solutions:
specify a route for /home and get done with it quickly
specify the 'redirectTo' or redirectPath attribute in the AuthController as follows:
In the AuthController.php
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectPath = '/myspecifiedroute';
...
...

i have a $redirectTo property in my AuthController, overriding the default redirect after successful login:
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
public $redirectTo = '/';
protected $loginPath = '/account/login';
...
I'm not really sure if it's $redirectTo or $redirectPath (at least according to the docs, i couldn't find this one in my project)
Further Reading

#hamza-ouaghad answer is the right answer for my problem. But I got another problem : my datas was not store in my database. When using laravel-mongodb and you need an unique field in your data model (like an email), you have to create a migration like :
Schema::create('users_collection', function($collection) {
$collection->unique('email');
});

Related

How do I fix the Laravel page not found error?

After registering, it redirects to / home. But I get a 404 error. When I set the route to / home, I get 302 continuous routing errors.
RegisterController.php
use RegistersUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest');
}
Route.php
Auth::routes(['verify' => true]);
Route::get('/', 'HomeController#index')->name('home');
HomeController
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
if you have in your HomeController's construct a middleware that requires the user to be logged in then what you are getting is normal.
You should have a login page wich use the "guest" middleware.
or
login the user automatically once he registers before redirecting him to your home route.
Auth::login($user)
//or
Auth::loginUsingId($userId);
Remove guest middleware.
public function __construct()
{
$this->middleware('guest');
}
Your HomeController should look like
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
your route.php Look like
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
RegisterController should look like
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
make sure you're following laravel authentication.

laravel multi authentication using admin roles

I've two types of users in my application. 'admins' & 'frontend users'. 'admin' has roles. i want redirect admins according to their roles. i've done the multiauth system but don't know how to redirect admins according to their roles.
here is admin model ->
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use Notifiable;
protected $guard = 'admin';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
// public function post(){
// return $this->hasOne('App\Post');
// }
public function role()
{
return $this->belongsTo('App\Role');
}
}
here is role model ->
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function admins()
{
return $this->hasMany('App\Admin');
}
}
here is the login controller for admins ->
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
use App\Admin;
use App\Role;
class BackendLoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest:admin', ['except' => ['logout']]);
}
public function showLoginForm()
{
return view('backEnd.backEnd-login');
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember))
{
return redirect()->intended(route('dashboard'));
}
return redirect()->back()->withInput($request->only('email', 'remember'));
}
public function logout()
{
Auth::guard('admin')->logout();
return redirect('/');
}
}
here is the login controller for users ->
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'userLogout']]);
}
public function userLogout()
{
Auth::guard('web')->logout();
return redirect('/');
}
}
routes ->
Route::get('/backend-login', 'Auth\BackendLoginController#showLoginForm')->name('backend.login');
Route::post('/backend-login', 'Auth\BackendLoginController#login')->name('backend.login.submit');
Route::get('/dashboard', 'BEController#index')->name('dashboard');
Route::get('/logout', 'Auth\BackendLoginController#logout')->name('backend.logout');
i've made guards and done the multiauth but can't set the role base system natively

BadMethodCallException, method getLogin doesn't exists l

I'm working on authentication and using the following code in routes.
Authentication routes:
Route::get('auth/login',['uses' => 'Auth\LoginController#getLogin']);
Route::post('auth/login',['uses' => 'Auth\LoginController#postLogin']);
Route::get('auth/logout',['uses' => 'Auth\LoginController#getLogout']);
I'm facing the following problem when I type in 'localhost:8000/auth/login':
BadMethodCallException
Method [getLogin] does not exist.`
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
`
How to solve this problem and where is getLogin method?
I'm using laravel 5.4.
Did you try with, it seem like method name is showLoginForm
Route::get('login', ['as' => 'login', 'uses' => 'Auth\LoginController#showLoginForm']);
Route::post('login', ['as' => 'login.post', 'uses' => 'Auth\LoginController#login']);
Route::post('logout', ['as' => 'logout', 'uses' => 'Auth\LoginController#logout']);
Or you can directly use auth method in router, it registered all the auth routes
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Routing/Router.php#L1007

NotFoundHttpException in Laravel middleware and controller

I am new to laravel and learning basics from https://www.tutorialspoint.com/laravel/laravel_middleware.htm
After installation I have created RoleMiddleware and TestController.
RoleMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $role)
{
echo "Role: ".$role;
return $next($request);
}
}
and TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class TestController extends Controller
{
//
public function index(){
echo "<br>Test Controller.";
}
}
and app\http\ routes.php
Route::get('/role',[
'middleware' => 'Role:editor',
'uses' => 'TestController#index',
]);
and in Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware \AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'Age' => \App\Http\Middleware\AgeMiddleware::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'Role' => \App\Http\Middleware\RoleMiddleware::class,
'terminate' => \App\Http\Middleware\TerminateMiddleware::class,
];
After written all these code I have executed this using http://localhost:8000/role but it gives NotFoundHttpException, Please help me to solve this issue..
First of all you are using some older version of Laravel, as your routes are listed in app\http\routes.php file because in newer versions, it is actually routes\web.php file:
Then you made a mistake in your route:
Route::get('/role', ['middleware' => 'Role:editor', 'uses' => ]);
http routes must have a callback/closure, whether it is custom function or using a controller... Try with following basic options:
Route::get('/role', function() { return "Working"; });
Also check whether your route is not listed as excepted route
If its working, then play with middlewares!!!
i cant send a comment to ask for hole error ( bcs of my reputation )
but i write middle ware in this way . maybe its help you :
first make sure that $role is string or put it in json_encode ( on RoleMiddleware.php )
==> echo "Role: ".json_encode($role);
then change your rout to below :
Route::get('/role', 'TestController#index')->middleware('Role');
send back to me the result

Method roles not found in laravel Auth

I keep getting the method not found error when I'm trying to assign a role to the user in the user registration section.
The following is the code that I am using in the AuthController
namespace App\Http\Controllers\Auth;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthController extends Controller
{
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
])->get();
$user->roles()->sync([2]);
return $user;
}
}
following is my User model
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\HasRole;
use App\Role;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $fillable = [
'first_name','last_name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
I'm not sure why this is happening. I think maybe it's not importing the User model properly, or I'm missing something. I'm new to laravel, so any help will be welcome.
To create a model simply use the following:
$user = User::create($attributes)
Notice that I did not call get() afterwords. get() will perform a query returning a Collection. I'm not sure what your Role model looks like, but it should work properly now.

Resources