PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 4, 2022

[FIXED] laravel-permission: assignRole works in Tinker but not in application

 March 04, 2022     assign, laravel-5, laravel-permission, permissions, user-permissions     No comments   

Issue

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?


Solution

Okay, I just could fix it. so simple when you know it. In AdministrationController.php, I replaced use Illuminate\Foundation\Auth\User; with use App\User;. That's it...



Answered By - Dong3000
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing