如何在单一登录表单laravel中重定向用户到用户页面和管理员到管理员页面


How to redirect a user to users page and admin to admin page in single login form laravel

我的数据库中有这个

|username|password|type|
------------------------
|foo     |12345   |1   |
|asd     |adsdsd  |0   |

这里1表示用户是管理员,0表示普通用户。

如何将管理员重定向到管理页面,将普通用户重定向到普通用户页面??

if($attempt)
{
    $id = User::find($attempt);
    $user = $id->type;
    if($user === 0)
    {
    return Redirect::action('LoginUsersController@profile');
    }
    else
    {
     return Redirect::to('adminpage');
    }
}

我在UsersController页面中创建了这个,我不知道这是否是正确的方法,我的代码也不起作用。

您使用的是普通的Laravel身份验证吗?

您将获得Object Auth::user(),这将返回当前用户Object。

它应该是这样的。

控制器(SessionsController@store)

public function store() {
    $input = Input::all();
    $attempt = Auth::attempt([
        'username' => $input['username'],
        'password' => $input['password']
    ]);
    if($attempt) {
        if(Auth::user()->type == 1) {
            return Redirect::admin(); // If admin, redirect to admin
        } else { 
            return Redirect::profile(); // Else, redirect to user profile
        }
    }
}

路线

Route::resource('sessions', 'SessionsController', ['only' => ['create','store','destroy']]);
Route::get('admin', 'AdminController@dashboard')->before('adminAuth'); 
Route::get('profile/{id}', 'UsersController@showProfile')->before('auth');

首先,您必须在用户表中添加一个新字段进行检查,例如"rank"。如果用户的级别为"1",则他是管理员,否则他就是一个普通用户。

然后在你的路线文件中定义所有需要的路线,如下所示:

Route::get('login', 'adminController@login');
Route::post('login', 'adminController@checkuser');
Route::group(array('before' => 'auth'), function() {
    Route::resource('admin', 'adminController'); 
    Route::resource('normaluser', 'normaluserController');
}  );

然后在您的控制器中,您必须定义所有操作:

public function login()
{
    return View::make('loginview');
}
public function checkuser()
{
    if (Auth::attempt(array('username'=>Input::get('username'), 'password'=>Input::get('password'))))
    {
        $user_data = Auth::getUser();
        if ($user_data->rank == 1)   //if true, so this user is an admin
        {return Redirect::to('admin');} //go to adminController index action            
        else         //if not, so he is a normal user
        {return Redirect::to('normaluser');} // go to normaluserController index action           
    }           
    else 
    {
        //return 'wrong user name or password';
        Session::flash('mismatch', "Username and Password mismatch");
        return Redirect::to('login'); // go again to login form to relogin
    }
}

如果有什么不清楚的地方,请毫不犹豫地询问。

在if语句中使用:

if($attempt)
{
    $id = User::find($attempt);
    $user = $id->type;
    if($user === 0)
    {
    return Redirect::action('LoginUsersController@profile');
    header('Location: http://www.example.com/userpahe.php');
    }
    else
    {
     return Redirect::to('adminpage');
     header('Location: http://www.example.com/admin-page.php');
    }
}