Laravel 5 check whether a user is logged in

Tartar picture Tartar · May 8, 2015 · Viewed 51.9k times · Source

I am new to Laravel 5 and trying to understand its Auth process. I want to prevent user to reach some of my pages unless the user is not logged in. Trying to make it with Route:filter but it does not work. What i have done wrong ?

Route::filter('/pages/mainpage', function()
{
    if(!Auth::check()) 
    {
        return Redirect::action('PagesController@index');
    }
});

Answer

lukasgeiter picture lukasgeiter · May 8, 2015

You should use the auth middleware. In your route just add it like this:

Route::get('pages/mainpage', ['middleware' => 'auth', 'uses' => 'FooController@index']);

Or in your controllers constructor:

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