Вызов функции-члена hasRole () в null - PullRequest
0 голосов
/ 14 октября 2018

Я новичок в Laravel

Я установил разрешения и роли в своем приложении и назначил их пользователям - однако, когда я пытаюсь использовать hasRole или hasAnyRole, это не работает для меня.

Вот мое промежуточное ПО CheckRole:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Get the required roles from the route
        $roles = $this->getRequiredRoleForRoute($request->route());
        // Check if a role is required for the route, and
        // if so, ensure that the user has that role.
        if($request->user()->hasRole('Admin','Receiptionist','Manager','CEO','Root')
        {
            return $next($request);
        }
        return response([
            'error' => [
                'code' => 'INSUFFICIENT_ROLE',
                'description' => 'You are not authorized to access this resource.'
            ]
        ], 401);
    }
    private function getRequiredRoleForRoute($route)
    {
        $actions = $route->getAction();
        return isset($actions['roles']) ? $actions['roles'] : null;
    }
}

Вот моя модель пользователя:

public function role()
{
    return $this->belongsToOne('App\Role', 'id', 'role_id');
}
public function hasRole($roles)
{
    $this->have_role = $this->getUserRole();
    // Check if the user is a root account
    if($this->have_role->name == 'Root') {
        return true;
    }
    if(is_array($roles)){
        foreach($roles as $need_role){
            if($this->checkIfUserHasRole($need_role)) {
                return true;
            }
        }
    } else{
        return $this->checkIfUserHasRole($roles);
    }
    return false;
}
private function getUserRole()
{
    return $this->role()->getResults();
}
private function checkIfUserHasRole($need_role)
{
    return (strtolower($need_role)==strtolower($this->have_role->name)) ? true : false;
}

А вот моя модель роли:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model


{
      protected $table = 'role';
      protected $fillable = ['name'];
      protected $primaryKey = 'id';
      public $timestamps = false;
public function users()
{
    return $this->belongsToMany('App\User', 'role_id', 'id');
}
}

Я пытаюсь запустить этот маршрут:

Route::group(['middleware'=>['authen','roles'],'roles'=>['Root']],function(){
//for Root

Route::get('/createUser',function(){
    echo "This is for Root test";
});

, который вызывает эту ошибку:

FatalThrowableError (E_ERROR) Вызов функции-члена hasRole () для null

1 Ответ

0 голосов
/ 07 февраля 2019

Если ваш код работал с первого раза, попробуйте добавить в Kernel.php одну строку и все будет хорошо, я думаю.Иметь хороший код, работающий над вашим проектом.:)

protected $middlewareGroups = [
    'CheckRole' => [
      \App\Http\Middleware\CheckRole::class,
      \Illuminate\Auth\Middleware\Authenticate::class,
],

Это означает, что вы пытаетесь проверить роль пользователя, но вы не вошли в систему до этого метода, что является причиной того, что вы получаете нулевое значение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...