Laravel 4路由受保护的页面

时间:2016-01-11 09:12:43

标签: laravel laravel-4 laravel-routing

我有一个控制器UserController.php,其中包含以下方法: getIndex(),getAll(),getCreate(),postStore(),getShow(),getEdit(),putUpdate(),getDestroy(),getLogin(),getDashboard()和getLogout()。

我已将以下代码包含在routes.php

    Route::get('/', function()
    {
    return View::make('hello');
    });
    Route::get('users/all/', [ 'as' => 'users.index', 'uses' => 'UserController@getAll']);
    Route::get('users/create/', [ 'as' => 'users.getCreate', 'uses' => 'UserController@getCreate']);
    Route::get('users/{all}/edit', 'UserController@getEdit');
    Route::put('users/update/{id}', [ 'as' => 'users.putUpdate', 'uses' => 'UserController@putUpdate']);
    Route::controller('users', 'UserController'); 

我可以访问

这样的页面
http://localhost/testlaravell/users/

http://localhost/testlaravell/users/add

现在,我希望只有登录的用户才能访问这些页面,其他方面他/她将重定向到登录页面http://localhost/testlaravell/login

UserController.php下登录的方法如下:

public function postSignin() {

        $rules = array(
        'username'    => 'required', // make sure the username is an actual username
        'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
        );

        // run the validation rules on the inputs from the form
        $validator = Validator::make(Input::all(), $rules);

        // if the validator fails, redirect back to the form
        if ($validator->fails()) {
        return Redirect::to('users/login')
        ->withErrors($validator) // send back all errors to the login form
        ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form

        } else {

        // create our user data for the authentication
        $userdata = array(
        'username'     => Input::get('username'),
        'password'  => Input::get('password')
        );

        // attempt to do the login
        if (Auth::attempt($userdata)) {


         return Redirect::to('users/dashboard')->with('message', 'Welcome User');

        } else {        

        // validation not successful, send back to form 
        return Redirect::to('users/login')->with('message', 'Sorry!! Username/ Password seems wrong.');

          }

     }       
 }

public function getLogin() {
    return View::make('users.login');
    }

1 个答案:

答案 0 :(得分:0)

您需要使用Laravel 4中的Auth Filter

您可以将所有路由包装在一个组中并指定该过滤器,在您的情况下,代码将是这样的。

WorkPage

您可以查看路线组here

上的文档