Laravel中间件重定向错误

时间:2016-09-17 03:23:43

标签: laravel

我有两个表用户和角色表,其各自的模型具有多对多关系。为他们提供包含' user_id'的数据透视表user_roles。和' role_id'专栏

这些是文件:

user.php的     

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Carbon\Carbon;

class User extends Authenticatable {

    protected $fillable = [ 'name', 'email', 'password'];
    protected $hidden = [
        'password',
        'remember_token'
    ];

    public function setPasswordAttribute($password) {
        $this->attributes['password'] = bcrypt($password);
    }

    public function setBirthdateAttribute($birthdate) {
        $this->attributes['birthdate'] = Carbon::createFromFormat('Y-m-d', $date);
    }


    public function roles() {
        return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
    }
}

Role.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users(){
        return $this->belongsToMany('App\User','user_roles','role_id','user_id');
    } 
}

我的中间件重定向问题是什么

这是我的中间件文件 RedirectIfAuthenticated.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\Guard;

class RedirectIfAuthenticated {

    protected $auth;

    public function __construct(Guard $auth) {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next) {
        if ($request->user() === null) {
            return response()->view('errors.401');
        } else {
            if ($this->auth->check()) {
//     ->                  don't have any algorithm here or any idea
                switch ($auth) {
                    case '1':
                        return redirect('home');
                        break;
                    case '2':
                        return redirect('admin');
                        break;
                    default:
                        return redirect('user');
                }
            }
            return $next($request);
        }
    }

    }

我的问题是我需要在上面的注释行中使用一段代码才能使这个代码正常工作。我的方法是检查当前登录用户的ID,该ID在user_roles表格中匹配&#39; role_id&#39;柱。感谢

1 个答案:

答案 0 :(得分:0)

用波纹管编辑的手柄功能替换手柄功能。

public function handle($request, Closure $next) {
    if ($this->auth->check()) {
        $auth = Auth::user()->roles()->first();

        switch ($auth->role) {
            case 'Blogger':                 
                return redirect('home');
                break;
            case 'Administrator':                   
                return redirect('admin');
                break;
            default:                    
                return redirect('user');
                break;
        }
    }
    return $next($request);
}