Php – Only allow certain ip addresses to register a user in Laravel 5.2

laravel-5.2PHP

I'm trying to only allow certain ip addresses to access the register route, but I'm getting Type error:

Argument 1 passed to
App\Http\Controllers\Auth\AuthController::showRegistrationForm() must
be an instance of Illuminate\Http\Request, none given, called in
directory\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php
on line 19

Here is my showRegistrationForm method in AuthController:

public function showRegistrationForm(Request $request) {
    $ip = $request->ip();

    if ($ip == "148.124.0.1") {
        return redirect("register");
    } else {
        return redirect("home");
    }
}

Does anyone know how I would accomplish this?

Best Answer

Instead checking in controller please check this way

php artisan make:middleware IpMiddleware

Code

<?php

namespace App\Http\Middleware;

use Closure;

class IpMiddleware
{

    public function handle($request, Closure $next)
    {
        if ($request->ip() != "192.168.0.155") {
        // here instead of checking a single ip address we can do collection of ips
        //address in constant file and check with in_array function
            return redirect('home');
        }

        return $next($request);
    }

}

then add the new middleware class in the $middleware property of your app/Http/Kernel.php class.

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'ipcheck' => \App\Http\Middleware\IpMiddleware::class,
];

then apply middelware to routes

Route::get('/', ['middleware' => ['ipcheck'], function () {
    // your routes here
}]);

I hope this helps!

Related Topic