jeudi 22 mars 2018

laravel-permission: assignRole works in Tinker but not in application

See my AdministrationController.php below:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Foundation\Auth\User;


class AdministrationController extends Controller
{

    public function index() {

        $user = User::find(1);
        $role = Role::where('name', 'owner')->get()->first();
        $user->assignRole($role);

    }

}

This is the important part of my User model:

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
    use Notifiable;
    ...
}

Curiously, the line $user->assignRole($role); in AdministrationController.php fires the following error:

BadMethodCallException
Method Illuminate\Database\Query\Builder::assignRole does not exist.

However, in Tinker this command sequence works fine and effects the desired result:

>>> $user=User::find(1)
>>> $role=Spatie\Permission\Models\Role::where('name', 'owner')->get()->first()
>>> $user->assignRole($role)

I googled for this issue, tried some fixing proposals but nothing helped me out. What's wrong in my AdministrationController.php / User.php?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire