Search code examples
laravelvoyager

Call to a member function relationLoaded() on string on voyage admin


I installed the voyager admin successfully from here

On my client page, I created a custom registration which is derived from auth. I can register the user successfully.

After I installed the voyager admin, I added a new user on client's registration form. Then, when i tried to access the http://localhost:8000/admin and then error occurred as seen on the image.

enter image description here

Below is the image of the line 53:

enter image description here

And below is the entire code of VoyagerUse.php

<?php

namespace TCG\Voyager\Traits;

use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use TCG\Voyager\Facades\Voyager;
use TCG\Voyager\Models\Role;

/**
 * @property  \Illuminate\Database\Eloquent\Collection  roles
 */
trait VoyagerUser
{
public function role()
{
    return $this->belongsTo(Voyager::modelClass('Role'));
}

/**
 * Check if User has a Role(s) associated.
 *
 * @param string|array $name The role to check.
 *
 * @return bool
 */
public function hasRole($name)
{
    if (!$this->relationLoaded('role')) {
        $this->load('role');
    }

    return in_array($this->role->name, (is_array($name) ? $name : [$name]));
}

public function setRole($name)
{
    $role = Voyager::model('Role')->where('name', '=', $name)->first();

    if ($role) {
        $this->role()->associate($role);
        $this->save();
    }

    return $this;
}

public function hasPermission($name)
{
    if (!$this->relationLoaded('role')) {
        $this->load('role');
    }

    if (!$this->role->relationLoaded('permissions')) {
        $this->role->load('permissions');
    }

    return in_array($name, $this->role->permissions->pluck('key')->toArray());
}

public function hasPermissionOrFail($name)
{
    if (!$this->hasPermission($name)) {
        throw new UnauthorizedHttpException(null);
    }

    return true;
}

public function hasPermissionOrAbort($name, $statusCode = 403)
{
    if (!$this->hasPermission($name)) {
        return abort($statusCode);
    }

    return true;
}
}

Solution

  • As mentioned in the VoyagerUser in line 53 :

    if(!$this->role->relationLoaded('permissions')){ ...
    

    The role here is considered as a relation not a field :)

    and the error

    Call to a member function relationLoaded() on string

    means that you have the role as attribute in the User Model

    So all you have to do is rename the role attribute to something else and everything will work perfectly ;)