1

I am trying to implement a very simple authentication mechanism with Laravel.

I need to protect certain routes so they are viewable from a specific IP address.

I want to do this:

if ($_SERVER['REMOTE_ADDR'] != '123.45.67.89') {
    return Redirect::away('some url');
}

How can I implement this with a guard?

1
  • Read the docs, implement your guard, ask again with any code you have that has errors/warnings/doesn't work as expected Commented Jan 8, 2020 at 14:07

1 Answer 1

1

You can achieve this by using middleware as it's used for what you're trying to do.

Create a new middleware by doing php artisan make:middleware SimpleGuardMiddleware. It will be created in app\Http\Middleware\SimpleGuardMiddleware.php.

Then, in the file you can write something like this:

public function handle($request, Closure $next)
{
    if ($request->ip() != '123.45.67.89') {
        return Redirect::away('some url');
    }
    return $next($request);
}

And then, go to app\Http\Kernel.php, make sure to add this to your protected $routeMiddleware array.

protected $routeMiddleware = [
    //.. your previous files ...
    'myguard' => SimpleGuardMiddleware.php::class,
];

And then in your route file, you can do something like

Route::group(['middleware' => 'auth'], function() {
    // your routes here...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Taylor. I already implemented this with middleware. Can I implement this with a guard?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.