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?
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...
}