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.
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');
#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.
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);
Related
I am getting a strange error which I cannot work out.
I have a User and also a Partner model. A user can have multiple partners. I am trying to retrieve a list of partners that the user has. I am also using Laravel Sanctum as my auth guard.
My relationship code is as follows;
In my user model
public function partners(): HasMany
{
return $this->hasMany(Partner::class);
}
In my Partner model
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
My route definition looks like so;
Route::middleware(['auth:sanctum'])->group(function () {
Route::apiResource('partners', Api\Partner\PartnerController::class)
->only(['index']);
});
and finally in my controller;
public function index(Request $request)
{
return PartnerResource::collection($request->user()->partners());
}
When I hit the endpoint though, I am getting the following error;
Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\HasMany::mapInto()
I cant figure out the issue. Any insight would be greatly appreciated.
When You are Calling user()->partners() it returns Illuminate\Database\Eloquent\Relations\HasMany Instance.
Resource needs to get Illuminate\Database\Eloquent\Collection Instance.
You have to just call user()->partners ( Remove parenthesis )
Or call get method on Illuminate\Database\Eloquent\Relations\HasMany Instance, to get Collection
user()->partners()->get()
I am trying to access my auth status in on a Model, i used an eloquent mutator to add a field to my model.
//use Illunimate\Facades\Support\Auth;
protected $appends = ['value'];
public function getValueAttribute(){ return Auth::user()->id()}
That is the code,
but its returning false even when logged in
You write the code in the wrong way. you miss the user() and then you use parentheses after id your code must be like this:
public function getValueAttribute(){ return Auth::user()->id;}
Corrected version of your code
public function getValueAttribute(){ return Auth::user()->id}
from your view you could check first to avoid crashes :
if (Auth::check()) {
// The user is logged in...
{{Auth::user()->id}}
}else{
// The user is NOT logged in...
}
Your code seems correct except its missing ;
So try this
use Illuminate\Support\Facades\Auth;
public function getValueAttribute(){ return Auth::user()->id();}
If that doesn't work try this alsophp artisan make:auth and then php artisan migrate
This will reset auth and migratation .
Hope this helps
I am currently trying to use this method
public function givePermissionTo(Permission $permission)
{
return $this->permissions()->save($permission);
}
So i can assign a permission to a role, for example:
$role->givePermissionTo(Permission::first());
However, what i get when trying to use that method is a bad method call exception.
My attempts to access that method were:
$role = Role::whereName('editor')->skip(1)->take(1)->get();
I have tried it in many other ways, but my problem is that i cannot get an instance of the Role Model, so i can access that method and give it the permission.
First of all, if you want to get a an exact role, you have to use first() method instead of get().
Try:
$role = Role::whereName('editor')->skip(1)->take(1)->first();
After assign the permission to the role you got:
$role->givePermissionTo(Permission::first());
I've used Eloquent hasOne to create a relationship between the user and the users_permissions table when the user register's to the website and group the user according to the input they put on the form and it worked fine, but the same method I think it does not recognize when the same user is signed in the website.
The below code work's when the user sign-up to the website
$user->permissions()->create(UserPermission::user_group($nature_of_entity));
But when I want to use the below method it, I get an error Trying to get property of non-object.
public function hasPermission($permission) {
return (bool) $this->permissions->$permission;
}
public function permissions() {
return $this->hasOne('App\User\UserPermission', 'user_id');
}
In the user database a table named users_permissions that has (id, user_id, is_group_one, is_group_two, is_group_three)
I'm trying to see it the user is in which group, like:
if($app->user->hasPermission('is_group_one')){
echo 'Group One';
}
But I get an error Trying to get property of non-object.
I'd really appreciate it if any can help and if they are ways I could do this and use Laravel Eloquent Relationships methods. I hope you can understand what I mean.
Create a scope that queries through the permissions relationship and checks if the column (i.e. $permission) is TRUE. Axe the (bool) bit...
public function scopeHasPermission($query, $permission)
{
return $query->permissions->where($permission, true);
}
Then in your controller, keep this the same as you had it:
if($app->user->hasPermission('is_group_one')) {
...
}
I am developing an application where I want to get all of a user's open tasks and display them. I have created a new view, route, controller and model, but I can't get the model to work right, especially as it pertains to getting the current user's ID for the SQL query.
app/models/Task.php
class Task extends Eloquent
{
public static function open()
{
$id = Auth::user()->id;
$tasks = DB::table('tasks')->where('c', 0)->where('user_id', $id)->get();
return $tasks;
}
}
Also
app/controllers/TaskController.php
public function open()
{
$tasks = Task::open();
return View::make('tasks.open')->with('tasks', $tasks);
}
Error: Trying to get property of non-object - looks like on the $id = Auth::user()->id;
What's the correct model?
Looks like not being logged in was the problem - this model works.
Because this will probably help someone else in the future: when you create a user's account, use Hash::make when you add the password to the database, because when you use Auth::attempt in your log in method, Laravel hashes password the user typed and compares the two, and if they're both not hashed, it won't log the user in.