laravel:使用Auth脚手架登录用户管理员时重定向到管理员

时间:2016-03-13 10:04:51

标签: php laravel authentication redirect user-roles

我正在尝试使用laravel为后端构建一个Web应用程序!我使用了php artisan make:auth命令来生成基本的登录逻辑和视图。现在我正在尝试根据数据库中users表中的admin字段重定向用户。问题是这样的:它认为我没有从数据库中获取正确的值,因此重定向永远不会起作用...

这是routes.php

Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/register', function () {
    return redirect('/step1');
});
route::get('/dashboard', function () {
    return view('admin.dashboard');
});
// after login --> else "welcome"
Route::get('/home', 'HomeController@index');
// register user + agency
Route::get('/step1', 'AgencyController@showStep1');
Route::post('/step1', 'Auth\AuthController@register');
// complete registration step 2 --> 9
Route::get('/step{stepId}', ['middleware' => 'auth', 'uses' => 'AgencyController@show']);
Route::post('/step{stepId}', 'AgencyController@store');});

以下是重定向的代码(在AuthController.php中)

<?php

namespace App\Http\Controllers\Auth;

use App\Agency;
use App\Http\Controllers\Controller;
use App\User; 
use Auth;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Validator;

class AuthController extends Controller {
/*
        |-------------------------------------------------------------------             -------
        | Registration & Login Controller
        |--------------------------------------------------------------------------
        |
        | This controller handles the registration of new users, as well as the
        | authentication of existing users. By default, this controller uses
        | a simple trait to add these behaviors. Why don't you explore it?
        |
*/

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

/**
 * Where to redirect users after login / registration.
 *
 * @var string
 */
protected $redirectTo = '/';

/**
 * Create a new authentication controller instance.
 *
 * @return void
 */
public function __construct() {
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}

public function login() {
    if (Auth::check()) {

        if (Auth::User()->admin != '1') {

            return redirect('/dashboard');
        } else {
            return redirect('/step1');
        }
    } else {return 'doesnt work :(';}
}

当我运行这个并登录时,我总是得到“不工作”的文字。

注意:Auth命令生成路由:

$this->get('login', 'Auth\AuthController@showLoginForm');
$this->post('login', 'Auth\AuthController@login');
$this->get('logout', 'Auth\AuthController@logout');

// Registration Routes...
$this->get('register', 'Auth\AuthController@showRegistrationForm');
$this->post('register', 'Auth\AuthController@register');
提前谢谢!

1 个答案:

答案 0 :(得分:1)

您使用的是laravel 4.2吗? 如果您想登录用户,似乎您需要手动登录, 你哼了

if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
    if(Auth::User()->admin != 1){
        #your logic
    }
    return Redirect::intended('dashboard');
}