In Laravel 5.2 after running their standard
> php artisan make:auth
let's assume we want to ensure user authentication when going to /admin
route.
In the routes.php
there will be an entry like this:
Route::group(['middleware' => ['web', 'auth']], function() {
// Only authenticated users may enter...
Route::get('/admin', [
'as' => 'admin', 'uses' => 'AdminController@index'
]);
});
and in AuthController.php
an additional method must be added:
class AuthController extends Controller
{
...
public function authenticated()
{
return redirect()->intended();
}
}
As a result every time when unauthenticated user tries to access /admin
URL it will be redirected to some /login
page and if authentication succeeds he will be able to access /admin
page.
A few points to notice in the code above:
- both
web
and auth
middleware groups are required (auth
without web
won't have session support and as a result url.intended
is not saved in the session and the whole redirect mechanism does not work)
- the method name in AuthController is
authenticated
and not authenticate
mentioned in Laravel documentation (it's called once authentication is verified)