'Call to a member function givePermissionTo() on null
I'm trying to learn Spatie Laravel Permission Package. When trying to insert data to models has permissions table it gives the below error in postman. I don't know clearly how to insert data. I used the guide of spatie documentation.
error,
Call to a member function givePermissionTo() on null
here is my controller function
public function models()
{
Role::create(['name'=>'writer']);
Permission::create(['name'=>'edit post']);
Auth::id()->givePermissionTo('edit articles');
return 'hello';
}
I don't know if the question is clear enough. Please tell me if it's not clear.
Solution 1:[1]
Auth::id() return the id of the authenticated user, but you need to call givePermissionTo on a user object, not a user id. try
Auth::user()->givePermissionTo('edit articles');
Solution 2:[2]
@brombeer was right. the issue was in the Auth::id()
It says the authenticated user is not accessed in.
I changed my function line Auth::id()->givePermissionTo('edit articles');
to auth()->user()->givePermissionTo('edit articles');
. Also the called __construct() function like this,
public function __construct()
{
$this->middleware('auth');
}
Then I accessed as an authorized user and inserted log in the token as a bearer token in postman. Then the issue was fixed.
Solution 3:[3]
Auth::id
returns the id of the user. The method givePermissionTo
should be called on an object of the user and not the id.
Here are two ways you can do it:
Method 1
Auth::user()->givePermissionTo('edit articles');
Method 2
$user = Auth::user();
$user->givePermissionTo('edit articles);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Majid Vahidkhoo |
Solution 2 | Tharindu Marapana |
Solution 3 | davidkihara |