ChatGPT解决这个技术问题 Extra ChatGPT

How to disable registration new users in Laravel

I'm using Laravel. I want to disable registration for new users but I need the login to work.

How can I disable registration form/routes/controllers?

Just remove the register-related methods from your routes.php file. Don’t override the methods with blank ones—it’s a horrible and hack-y approach as you’ve then got to re-add the bodies if you decide to re-enable that feature in the future.
@MartinBean there are no routes in routes.php. To enable the authentication functions, all you do is add Route::auth(); to the file.
@miken32 My comment was from over five months ago, before the Route::auth() shortcut was advocated.
if you are in laravel 5.5 and above Auth::routes(['register' => false]); in web.php

m
milo526

Laravel 5.7 introduced the following functionality:

Auth::routes(['register' => false]);

The currently possible options here are:

Auth::routes([
  'register' => false, // Registration Routes...
  'reset' => false, // Password Reset Routes...
  'verify' => false, // Email Verification Routes...
]);

For older Laravel versions just override showRegistrationForm() and register() methods in

AuthController for Laravel 5.0 - 5.4

Auth/RegisterController.php for Laravel 5.5

public function showRegistrationForm()
{
    return redirect('login');
}

public function register()
{

}

It might be wise to also change the create() function to: throw new Exception('Registration not possible');
or you can add abort(404) on function register()
I wouldn’t advocate this approach, as overloading code to remove a feature is never a good thing. Just don’t register the registration-related routes.
For Laravel 5.5, put this in Auth/RegisterController.php
In Laravel 5.7 showRegistrationForm() function is in vendor folder, technically it's not recommended to edit files in vendor folder. Basically what I recommend is to remove register route from web.php. You can simply say Auth::routes(['register' => false]) in web.php file. Cheers!
m
miken32

This might be new in 5.7, but there is now an options array to the auth method. Simply changing

Auth::routes();

to

Auth::routes(['register' => false]);

in your routes file after running php artisan make:auth will disable user registration.


Thanks for this, I don't know since which version it exists, but I think it is the right path for disabling registration part !
It was added in 5.7.
Disable Register Route in Laravel 7 / 8
R
Rafał G.

If you're using Laravel 5.2 and you installed the auth related functionality with php artisan make:auth then your app/Http/routes.php file will include all auth-related routes by simply calling Route::auth().

The auth() method can be found in vendor/laravel/framework/src/Illuminate/Routing/Router.php. So if you want to do as some people suggest here and disable registration by removing unwanted routes (probably a good idea) then you have to copy the routes you still want from the auth() method and put them in app/Http/routes.php (replacing the call to Route::auth()). So for instance:

<?php
// This is app/Http/routes.php

// Authentication Routes...
Route::get('login', 'Auth\AuthController@showLoginForm');
Route::post('login', 'Auth\AuthController@login');
Route::get('logout', 'Auth\AuthController@logout');

// Registration Routes... removed!

// Password Reset Routes...
Route::get('password/reset/{token?}', 'Auth\PasswordController@showResetForm');
Route::post('password/email', 'Auth\PasswordController@sendResetLinkEmail');
Route::post('password/reset', 'Auth\PasswordController@reset');

If you're using lower version than 5.2 then it's probably different, I remember things changed quite a bit since 5.0, at some point artisan make:auth was even removed IIRC.


Instead of remove the registration routes, is it possible to enable them only for a particular type of users?
@Sefran2 You can achieve this by associating groups with middleware. Check out laravel.com/docs/5.2/routing#route-groups
First of all, I tried Route::group(['middleware' => 'auth'], function () { Route::get('register', 'Auth\AuthController@showRegistrationForm'); Route::post('register', 'Auth\AuthController@register'); });, but when the logged user requests /register he is redirected to /
@Sefran2 That's because AuthController calls (via other classes and traits, it's a little convoluted) the middleware App\Http\Middleware\RedirectIfAuthenticated. And that middleware redirects you to / if you're already logged in. Which makes sense, why would you want to register if you're logged in? :-) If you want to only allow some routes to some types of users, you'll need to create your own middleware instead of ['middleware' => 'auth']
For 5.3 they are different once again, but can still be found in vendor/laravel/framework/src/Illuminate/Routing/Router.php
Y
Yassin

For Laravel 5.3 and 5.4, here is the proper way to do it:

You have to change:

public function __construct()
    {
        $this->middleware('guest');
    }

to

public function __construct()
    {
        $this->middleware('auth');
    }

in app/Http/Controller/Auth/RegisterController.php


nice job! I think this way also protects from POST request for creating user via post?
this will allow registered users to see the registration page which you would not want
Use middleware("auth") then middleware("guest") to bypass registration page for everyone
then a auth user can register a new user in this case.
Yes this is the only proper way for anything below 5.7 .. how is this not the selected answer
C
Christopher Geary

As of Laravel 5.7 you can pass an array of options to Auth::routes(). You can then disable the register routes with:

Auth::routes(['register' => false]);

You can see how this works from the source code: src/Illuminate/Routing/Router.php.


In my opinion, this is the correct answer. Nice found!
A
Abed Putra

Method 1 for version 5.3

In laravel 5.3 don't have AuthController. to disable register route you should change in constructor of RegisterController like this:

You can change form:

public function __construct()
{

    $this->middleware('guest');

}

to:

use Illuminate\Support\Facades\Redirect;

public function __construct()
{

    Redirect::to('/')->send();

}

Note: for use Redirect don't forget to user Redirect; So user access to https://host_name/register it's redirect to "/".

Method 2 for version 5.3

When we use php artisan make:auth it's added Auth::route(); automatically. Please Override Route in /routes/web.php. You can change it's like this: * you need to comment this line: Auth::routes();

    <?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/


// Auth::routes();
Route::get('/login', 'Auth\LoginController@showLoginForm' );
Route::post('/login', 'Auth\LoginController@login');
Route::post('/logout', 'Auth\LoginController@logout');

Route::get('/home', 'HomeController@index');

Thanks! I hope it's can solve your problems.


I would add route names like specified in vendor/laravel/framework/src/Illuminate/Routing/Router.php Route::get('login', 'Auth\LoginController@showLoginForm')->name('login'); Route::post('login', 'Auth\LoginController@login'); Route::post('logout', 'Auth\LoginController@logout')->name('logout');
Redirect class missed on the first method, but changing to $this->middleware('auth'); - works!
J
JCoolinger

Overwriting the getRegister and postRegister is tricky - if you are using git there is a high possibility that .gitignore is set to ignore framework files which will lead to the outcome that registration will still be possible in your production environment (if laravel is installed via composer for example)

Another possibility is using routes.php and adding this line:

Route::any('/auth/register','HomeController@index');

This way the framework files are left alone and any request will still be redirected away from the Frameworks register module.


The classes that override the framework methods are not in the framework (they would be in the app folder) and would be stored by git. Overriding methods does not mean you change them in the framework files.
I
Isaac Limón

LAravel 5.6

Auth::routes([
    'register' => false, // Registration Routes...
    'reset' => false, // Password Reset Routes...
    'verify' => false, // Email Verification Routes...
]);

This should be merged into the accepted answer, but just a minor correction. This feature was introduced in Laravel 5.7, not Laravel 5.6
R
Randika Vishman

The AuthController.php @limonte has overridden is in App\Http\Controllers\Auth, not in the vendor directory, so Git doesn't ignore this change.

I have added this functions:

public function register() {
    return redirect('/');
}

public function showRegistrationForm() {
    return redirect('/');
}

and it works correctly.


V
Vinay Kaithwas

Set Register route false in your web.php.

Auth::routes(['register' => false]);

k
kjdion84

Heres my solution as of 5.4:

//Auth::routes();
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
//Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
//Route::post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');

Notice I've commented out Auth::routes() and the two registration routes.

Important: you must also make sure you remove all instances of route('register') in your app.blade layout, or Laravel will throw an error.


^ this. In case these routes ever change, simply copy/paste them from the Auth routes bundle located @ github.com/laravel/framework/blob/… and comment out the registration routes.
R
Randika Vishman

The following method works great:

Copy all the routes from /vendor/laravel/framework/src/Illuminate/Routing/Router.php and paste it into web.php and comment out or delete Auth::routes().

Then setup a conditional to enable and disable registration from .env. Duplicate the 503.blade.php file in views/errors and create a 403 forbidden or whatever you like.

Add ALLOW_USER_REGISTRATION= to .env and control user registration by setting its value to true or false.

Now you have full control of routes and Vendor files remain untouched.

web.php

//Auth::routes();

// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
if (env('ALLOW_USER_REGISTRATION', true))
{
    Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
    Route::post('register', 'Auth\RegisterController@register');
}
else
{
    Route::match(['get','post'], 'register', function () {
        return view('errors.403');
    })->name('register');
}

// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');

This is a combination of some previous answers notably Rafal G. and Daniel Centore.


D
Daniel Centore

In routes.php, just add the following:

if (!env('ALLOW_REGISTRATION', false)) {
    Route::any('/register', function() {
        abort(403);
    });
}

Then you can selectively control whether registration is allowed or not in you .env file.


v
vimuth

On laravel 5.6 and above you can edit in web.php file

Auth::routes(['verify' => true, 'register' => false]);

and you can make it true if you change your mind, i see it easy this way


E
Edvard Åkerberg

This has been mentioned in earlier comments but I would like to clarify that there are multiple ways to access the auth routes in your web.php file in Laravel ^5.7. depending on your version it might look a little different but they achieve the same result.

First option

Route::auth([
  'register' => false, // Registration Routes...
  'reset' => false, // Password Reset Routes...
  'verify' => false, // Email Verification Routes...
]);

Second option

Auth::routes([
  'register' => false, // Registration Routes...
  'reset' => false, // Password Reset Routes...
  'verify' => false, // Email Verification Routes...
]);

g
ghodder

I had to use:

public function getRegister()
{
    return redirect('/');
}

Using Redirect::to() gave me an error:

Class 'App\Http\Controllers\Auth\Redirect' not found

Thank you, yes this is new version feature, you can use this function or use preceding class, but preceding class needs \ before it, I means \Redirect::to('destination');
b
bambamboole

In Laravel 5.4

You can find all routes which are registered through Auth::routes() in the class \Illuminate\Routing\Router in the method auth()

it looks like this:

/**
 * Register the typical authentication routes for an application.
 *
 * @return void
 */
public function auth()
{
    // Authentication Routes...
    $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
    $this->post('login', 'Auth\LoginController@login');
    $this->post('logout', 'Auth\LoginController@logout')->name('logout');

    // Registration Routes...
    $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
    $this->post('register', 'Auth\RegisterController@register');

    // Password Reset Routes...
    $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
    $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
    $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
    $this->post('password/reset', 'Auth\ResetPasswordController@reset');
}

Just copy the routes that you want/need and you are fine!


T
The Billionaire Guy

In laravel 5.3, you should override the default showRegistrationForm() by including the code below into the RegisterController.php file in app\Http\Controllers\Auth

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showRegistrationForm()
    {
        //return view('auth.register');
         abort(404);  //this will throw a page not found exception
    }

since you don't want to allow registration, it's better to just throw 404 error so the intruder knows he is lost. And when you are ready for registraation in your app, uncomment //return view('auth.register'); then comment abort(404);

\\\\\\\\\\\\\\\\\\\\JUST AN FYI///////////////////////////////

If you need to use multiple authentication like create auth for users, members, students, admin, etc. then i advise you checkout this hesto/multi-auth its an awesome package for unlimited auths in L5 apps.

You can read more abouth the Auth methodology and its associated file in this writeup.


You also need to patch the post route so to avoid registration of user through post request.
D
David Angel

In Laravel 5.5

I was trying to accomplish the same problem in Laravel 5.5. Instead of using Auth::routes() in the web.php routes file, I only included the login/logout routes:

Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

c
codewithfeeling

If you are using Laravel 8 with Laravel Breeze, these auth routes are all explicitly listed in routes/auth.php. The registration routes are the first two at the top.

Just comment out the ones you don't want and Laravel takes care of the rest, eg. if you comment out the routes for forgot-password then there will be no "Forgot password?" link shown on the login window.


M
Motolola

In order not too change the code as it is, just create a middleware to detect if the request url is url('register'), then redirect to 404 or do wherever.


Very long run solution. A simple function override with abort can definitely work.
C
Chad Quilter

In Laravel 5.5

Working on a similar issue and setting the middleware argument from guest to 'auth' seemed like a more elegant solution.

Edit File: app->http->Controllers->Auth->RegisterController.php

public function __construct()
{
     //replace this
     //$this->middleware('guest');

     //with this argument.
       $this->middleware('auth');
}

I could be wrong though...but it seems more slick than editing the routing with more lines and less shity than simply redirecting the page...at least in this instance, wanting to lock down the registration for guests.


I'd be curious to know whether a user can register multiple times using this method. the guest middleware is responsible redirecting an already logged in user away from a page that only a guest can access (i.e. a /register page)
V
Vaishnav Mhetre

I guess this would rather be a better solution.

Override the following methods as below mentioned in

App\Http\Controller\Auth\RegisterController.php

use Illuminate\Http\Response;

.
.
.

public function showRegistrationForm()
{
    abort(Response::HTTP_NOT_FOUND);
}

public function register(Request $request)
{
    abort(Response::HTTP_NOT_FOUND);
}

m
macalu

In Laravel 5.5 is very simple, if you are using CRUD route system.

Go to app/http/controllers/RegisterController there is namespace: Illuminate\Foundation\Auth\RegistersUser

You need to go to the RegistersUser: Illuminate\Foundation\Auth\RegistersUser

There is the method call showRegistrationForm change this: return view('auth.login'); for this: return redirect()->route('auth.login'); and remove from you blade page route call register. It may look like that:

 <li role="presentation">
     <a class="nav-link" href="{{ route('register') }}">Register</a>
 </li> 

R
Ryan Dhungel

I found this to be the easiest solution in laravel 5.6! It redirects anyone who tries to go to yoursite.com/register to yoursite.com

routes/web.php

// redirect from register page to home page
Route::get('/register', function () {
    return redirect('/');
});

A
Alien

All I did was replace register blade code with login blade code. That way register still goes to login.

resources/views/auth/register.blade.php is replaced with resources/views/auth/login.blade.php


Y
Yamen Ashraf

For Laravel 5.6+, paste the below methods in app\Http\Controller\Auth\RegisterController

/*
* Disabling registeration.
*
*/
public function register() 
{
    return redirect('/');
}

/*
* Disabling registeration.
*
*/
public function showRegistrationForm() 
{
    return redirect('/');
}

Now you're overriding those methods in RegistersUser trait, whenever you change your mind remove these methods. You may also comment the register links in welcome.blade.php and login.blade.php views.


h
hungtran273

For Fortify users, change config/fortify.php

'features' => [
    // Features::registration(), // --------> comment out this
    Features::resetPasswords(),
    // Features::emailVerification(),
    Features::updateProfileInformation(),
    Features::updatePasswords(),
    Features::twoFactorAuthentication(),
],

k
karrar kazuya

for laravel with fortify like in (Laravel v8.52.0) you can just disable the registration feature in the fortify config file, for example

'features' => [
    //Features::registration(),
    //Features::resetPasswords(),
    // Features::emailVerification(),
    Features::updateProfileInformation(),
    Features::updatePasswords(),
    Features::twoFactorAuthentication([
        'confirmPassword' => true,
    ]),
]

This was literally the last answer left on the question, 2 months ago.
s
sjas

add

use \Redirect;

at the top of the file


You mean use \Redirect;
This is not a complete answer.
at the top of which file? the solution is incomplete and confusing.