I'm new to Laravel and I inherited a project. I saw that there was a app/Http/Controller/Auth/RegisterController.php, but going to the websites /register gave me a 404 error. So I added this line to routes/web.php
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
And now I can go to the url /register and sign up a new user without any issues.
I went into resources/views/auth/login.blade.php and added the line
Don't have an account? Sign up
But this gave me an error Route [register.create] not defined. View(.. path to login.blade.php
What did I do wrong?
Answer
The reason why you it's returning a 404 is because when you manually register the registration routes and you do it before the Auth::routes which registers one with the same key that overwrites yours. Hence why it's working if you move them after the Auth::routes.
What you could do is disable the register routes from the Auth facade:
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
Auth::routes(['register' => false]);
If you plan on using Laravel's default registration system, you simply have to remove your manually registered routes and create the respective views and you can access the route with route('register');.
You can also check the other available routes generated by the Auth facade with php artisan route:list.
Note
Also, you do not need to group them in the web middleware when adding routes in routes/web.php because they are automatically in the middleware by the RouteServiceProvider.
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
I solved the problem. I made a guess changed this:
Route::group(['middleware' => ['web']], function () {
... other code ...
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
Auth::routes();
... other code ...
});
To this
Route::group(['middleware' => ['web']], function () {
... other code ...
Auth::routes();
... other code ...
});
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
And it worked. NOt sure if this is the right way to do it though
Related
This question already has answers here:
Error “Target class controller does not exist” when using Laravel 8
(27 answers)
Closed 1 year ago.
When I run `php artisan route:list' I get an error it can't find the RegisterController from the auth scaffolding.
Illuminate\Contracts\Container\BindingResolutionException : Target class [App\Http\Controllers\Auth\RegisterController] does not exist.
at C:\xampp\htdocs\antheap\vendor\laravel\framework\src\Illuminate\Container\Container.php:805
801|
802| try {
803| $reflector = new ReflectionClass($concrete);
804| } catch (ReflectionException $e) {
> 805| throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
806| }
807|
808| // If the type is not instantiable, the developer is attempting to resolve
809| // an abstract type such as an Interface or Abstract Class and there is
Exception trace:
1 Illuminate\Foundation\Console\RouteListCommand::Illuminate\Foundation\Console\{closure}(Object(Illuminate\Routing\Route))
[internal]:0
2 ReflectionException::("Class App\Http\Controllers\Auth\RegisterController does not exist")
C:\xampp\htdocs\antheap\vendor\laravel\framework\src\Illuminate\Container\Container.php:803
Which makes sense considering the RegisterController.php file is in Controllers/Web/Auth/ and its namespace is namespace App\Http\Controllers\Web\Auth;
I'm guessing it's looking for the wrong place because of default routing in the illuminate framework. However all the other Auth controllers are functioning fine. I'm not keen on moving everything just to make the list route:list command happy, though I kinda need it not crashing right now to help fix some other issue.
I've changed the Auth helper in web.php and added the auth routes:
// helper class generating all routes required for user authentication
// (authentication, registration and password resetting)
Auth::routes(['verify' => true, 'register' => false]);
Route::get('/login', 'Auth\LoginController#showLoginForm')->name('login');
Route::post('/login', 'Auth\LoginController#login');
Route::get('/logout', 'LoginController#logout')->name('logout');
Route::group(['middleware' => 'auth'], function () {
Route::get('/password/confirm', 'Auth\ConfirmPasswordController#showConfirmForm')->name('password.confirm');
Route::post('/password/confirm', 'Auth\ConfirmPasswordController#confirm');
});
Route::post('/password/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email');
Route::get('/password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.request');
Route::post('/password/reset', 'Auth\ForgotPasswordController#reset')->name('password.update');
Route::get('/password/password/reset/{token}', 'ResetPasswordController#showResetForm')->name('password.reset');
Route::group(['middleware' => 'guest'], function () {
Route::get('/password/register', 'Auth\RegisterController#showRegistrationForm')->name('register');
Route::post('/password/register', 'Auth\RegisterController#register');
});
However, this still doesn't allow for route:list to work correctly. The weird thing is I can comment out routes from about and they would still work normally (I assume covered by the default ones). Using route:clear doesn't change anything.
I can also add or remove the Auth\ in front of the Controller name, this doesn't keep it from working , nor will it fix route:list
But the app is definitely using it because if I change the URI suffix (like 'login' to 'logintest', it will show that in the browser address.
One thing that I forget to mention is that in RouteServiceProvide.php I added the \Web namespace (I don't know how route:list deals with that?)
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* #return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace . '\Web')
->group(base_path('routes/web.php'));
}
This because I had to break up the route file at some point into multiple ones with their own namespaces. And I put the Auth inside the Web routes due to many of its routes using limited to no middleware.
Problem is that taking Auth from the web folder and namespace just breaks way more than just route:list.
Ok I solved it, but not in a pretty way by moving back all the auth controllers to the folder route:list was looking for and just adding another separate routing file solely for auth
RouteServiceProvider.php
protected function mapAuthRoutes()
{
Route::middleware('web')
// ->namespace($this->namespace . '\Auth')
->group(base_path('routes/auth.php'));
}
I commented out the \Auth namespace because with testing it didn't seem to work properly
And then routes/auth.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
/*
|--------------------------------------------------------------------------
| Auth Routes
|--------------------------------------------------------------------------
|
*/
// helper class generating all routes required for user authentication
// (authentication, registration and password resetting)
// Auth::routes(['verify' => true, 'register' => false]);
Route::get('/login', 'App\Http\Controllers\Auth\LoginController#showLoginForm')->name('login');
Route::post('/login', 'App\Http\Controllers\Auth\LoginController#login');
Route::post('/logout', 'App\Http\Controllers\Auth\LoginController#logout')->name('logout');
Route::group(['middleware' => 'auth'], function () {
Route::get('/password/confirm', 'App\Http\Controllers\Auth\ConfirmPasswordController#showConfirmForm')->name('password.confirm');
Route::post('/password/confirm', 'App\Http\Controllers\Auth\ConfirmPasswordController#confirm');
});
Route::post('/password/email', 'App\Http\Controllers\Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email');
Route::get('/password/reset', 'App\Http\Controllers\Auth\ForgotPasswordController#showLinkRequestForm')->name('password.request');
Route::post('/password/reset', 'App\Http\Controllers\Auth\ForgotPasswordController#reset')->name('password.update');
Route::get('/password/password/reset/{token}', 'App\Http\Controllers\Auth\ResetPasswordController#showResetForm')->name('password.reset');
Route::group(['middleware' => 'guest'], function () {
Route::get('/password/register', 'App\Http\Controllers\Auth\RegisterController#showRegistrationForm')->name('register');
Route::post('/password/register', 'App\Http\Controllers\Auth\RegisterController#register');
});
I had to completely write out the paths for the controllers or it wouldn't work
And the namespace used in the auth controllers (which is also the file path):
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
I don't feel like this was the cleanest solution, and I would love to know why route:list doesn't seem to understand the namespacing used before. But at least it's working again now.
I was working in laravel 8.x, I have developed API to register, but when i test using postman also in browser the url [1]: http://127.0.0.1:8000/api/register always returns 404 not found message.
below is my api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['prefix' => 'v1'], function () {
Route::post('/login', 'UsersController#login');
Route::post('/register', 'UsersController#register');
Route::get('/logout', 'UsersController#logout')->middleware('auth:api');
});
can you please help?
Since you already put a route group "v1", all your routes must have that prefix, so just api/register wont work because that route doesn't exist inside your api.php, so infront of your routes just use
http://127.0.0.1:8000/api/v1/register
http://127.0.0.1:8000/api/v1/login
http://127.0.0.1:8000/api/v1/logout
Your routes looking fine.
I think you are forgetting to add http://127.0.0.1:8000/api/**v1**/register so please try with it once.
What is the correct way to authenticate all routes except login and register when I apply auth middleware in all controllers? Is there a way to apply auth middleware in one place and exclude login, register routes?
You can group all your authenticated routes like following, laravel provides a default middleware for auth and guest users
Route::group(['middleware' => ['auth']], function () {
Route::get('home', 'HomeController#index');
Route::post('save-user', 'UserController#saveUser');
Route::put('edit-user', 'UserController#editUser');
});
The above route names are just made up, please follow a proper naming convention for your routes and controllers. Also read about middlewares over here and about routing over here
you can apply middlewares in the routes.php file, what you need to do is to put all your routes on a group, and add the middleware 'auth' ( except the Auth::routes() which are already configured), for example :
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Uses first & second Middleware
});
Route::get('user/profile', function () {
// Uses first & second Middleware
});
});
more information can be found in the docs: https://laravel.com/docs/5.7/routing#route-group-middleware
You can add middleware to your whole web.php route file by adding the middleware to your routes mapping in RouteServiceProvider.
Go to app/Providers/RouteServiceProvider.php and in mapWebRoutes(), change middleware('web') to middleware(['web', 'auth']):
protected function mapWebRoutes()
{
Route::middleware(['web', 'auth'])
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
This is (not?) totally unrelated but here's an example of a clean way to handle a lot of route files instead of throwing all your routes into a single web.php file:
Create a new method mapAdminRoutes():
protected function mapAdminRoutes()
{
Route::middleware(['web', 'auth:admin'])
->namespace('App\Http\Controllers\Admin')
->name('admin.')
->group(base_path('routes/admin.php'));
}
Map it:
public function map()
{
$this->mapWebRoutes();
$this->mapAdminRoutes(); // <-- add this
...
}
Create an admin.php file in your routes folder, then create your routes for Admin:
<?php
use Illuminate\Support\Facades\Route;
// This route's name will be 'admin.dashboard'
Route::get('dashboard', 'DashboardController#dashboard')->name('dashboard');
// This route's name will be 'admin.example'
Route::get('example', 'ExampleController#example')->name('example');
...
Now you can configure everything in 1 place, like prefix, name, middleware and namespace.
Check php artisan route:list to see the results :)
I am using Larave 5 for my project. In my project i am using laravel default auth which use this command php artisan make:auth. And i set middleware in my route.php as shown
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::auth();
Route::get('/', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
// Admin Roles Routes...
Route::get('admin/roles', 'AdminController#showRoles');
});
Now my question is if i user is logout and click on browser back button user login and user can access like add, edit, delete view after logout. So how can i handle this situation. Please help i think some code i miss out.
First of all, your Route::auth() does already has login and logout functions, if you run 'php artisan route:list' in your terminal you can see which routes are available etc..
Second of all you can create a group like shown below for your admin stuff:
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::auth();
// Admin Roles Routes...
Route::group(['prefix'=>'admin', 'middleware'=>'auth'], function() {
Route::get('roles', 'AdminController#showRoles');
});
});
I hope this works for you ;)
Btw, the Laravel docs tell you a lot..., so make sure you watch them first ;)
First thing is you don't need to apply web middleware as it already applied to your routes by RouteServiceProvider, see https://laravel.com/docs/5.2/middleware#registering-middleware
Secondly, when use Route:auth() it is a shortcut for:
$this->get('login', 'Auth\AuthController#showLoginForm');
$this->post('login', 'Auth\AuthController#login');
$this->get('logout', 'Auth\AuthController#logout');
$this->get('register', 'Auth\AuthController#showRegistrationForm');
$this->post('register', 'Auth\AuthController#register');
$this->get('password/reset/{token?}', 'Auth\PasswordController#showResetForm');
$this->post('password/email', 'Auth\PasswordController#sendResetLinkEmail');
$this->post('password/reset', 'Auth\PasswordController#reset');
So you don't need to define these routes:
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
Lastly, why you put login on your home page?
Route::get('/', 'Auth\AuthController#getLogin');
This example should be work:
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
return 'Hello! You are logged in.';
});
// Admin Roles Routes...
Route::get('admin/roles', 'AdminController#showRoles');
});
Route::auth();
With the routes above when unauthenticated user trying to access your home page http://yoursite.com and http://yoursite.com/admin/roles, user will be redirected to http://yoursite.com/login since those pages are protected by auth middleware.
An addition to #Rick answer.
You can also manually set a middleware inside the __construct() function of your controller.
Example:
// SomeController.php
public function __construct()
{
$this->middleware('auth');
}
Documentation
i am new to laravel,
i have code in my controller's __construct like
if(Auth::check())
{
return View::make('view_page');
}
return Redirect::route('login')->withInput()->with('errmessage', 'Please Login to access restricted area.');
its working fine, but what i wants is. its really annoying to put these coding in each and every controller, so i wish to put this Verify Auth and redirect to login page in one place, may be in router.php or filters.php.
I have read some posts in forum as well as in stackoverflow, and added code in filters.php like below but that's too not working.
Route::filter('auth', function() {
if (Auth::guest())
return Redirect::guest('login');
});
Please help me to resolve this issue.
Laravel 5.4
Use the built in auth middleware.
Route::group(['middleware' => ['auth']], function() {
// your routes
});
For a single route:
Route::get('profile', function () {
// Only authenticated users may enter...
})->middleware('auth');
Laravel docs
Laravel 4 (original answer)
That's already built in to laravel. See the auth filter in filters.php. Just add the before filter to your routes. Preferably use a group and wrap that around your protected routes:
Route::group(array('before' => 'auth'), function(){
// your routes
Route::get('/', 'HomeController#index');
});
Or for a single route:
Route::get('/', array('before' => 'auth', 'uses' => 'HomeController#index'));
To change the redirect URL or send messages along, simply edit the filter in filters.php to your liking.
To avoid code repetition, You can use it in middleware. If you are using the Laravel build in Auth, You can directly use the auth middleware as given,
Route::group(['middleware' => ['auth']], function() {
// define your route, route groups here
});
or, for a single route,
Route::get('profile', function () {
})->middleware('auth');
If you are building your own, custom Authentication system. You should use the middleware which will check the user is authenticated or not. To create custom middleware, run php artisan make:middleware Middelware_Name_Here and register the newly created middleware.
It's absolutely correct what other people have replied.
This solution is for Laravel 5.4
But just in case, if you have more than one middleware applying to routes, make sure 'auth' middleware comes in the end and not at the start.
Like this:
Route::prefix('/admin')->group(function () {
Route::group(['middleware' => 'CheckUser', 'middleware' => 'auth'], function(){
});
});
Route::middleware(['auth'])->group(function () {
Route::get('dashboard','BackendController#dashboard')->name('dashboard');
});
This entry in the web.php route will take the user [who is not logged in] to the login page if (s)he tries to access a 'protected' URL, "dashboard" in this case.