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
Related
I'm working with Laravel 8.5 and I wanted to develop my own ACL.
So I made this ManyToMany relationship between Permission & User models:
User.php:
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
Permission.php:
public function users()
{
return $this->belongsToMany(User::class);
}
Then I have inserted this custom permission into permissions table:
And then inserted this also into the pivot table pemrission_user:
Then at web.php, I tried this:
Route::get('/', function () {
$user = auth()->user();
// dd($user->permissions()->get());
if(Gate::allows('edit-user')){
dd(2);
}else{
dd(1);
}
});
So I tried checking if the logged in user has the permission edit-user, then shows 2 as result but now it returns 1 somehow, meaning that user has not this permission!
However if I uncomment dd($user->permissions()->get());, I can see this:
So as it shows user already has this edit-user permission but I don't why the Gate does not authorize user in this case.
So if you know, I beg you to help me cause I really don't know how to solve this...
You need to define edit-user for your Gate as well because your permission model means nothing to the Gate at the moment.
Gate::define('edit-user', function (User $user) {
return $user->permissions()->whereName('edit-user')->exists();
});
More information can be found here: https://laravel.com/docs/8.x/authorization#writing-gates
Otherwise, you can use policies:
class UserPolicy
{
public function update(User $user)
{
return $user->permissions()->whereName('edit-user')->exists();
}
}
And then to allow the user:
$user->can('update', User::make());
More information about policies can be found here: https://laravel.com/docs/master/authorization#creating-policies
There's also an open source package called laravel-permission made by Spatie that you can have a look at to learn more.
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);
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 was simply trying to log out admin user from the Dashboard while I used this code for doing it:
Routes.php
Route::get('logout',array('uses'=>'AuthController#LogOut'));
AuthController.php
class AuthController extends Controller{
public function LogOut(){
Auth::logout();
return Redirect::to('login');
}
}
while it is giving me such error for log out
as i don't have such field in Database, and also it is not added to Database while Migration also.
The error is most likely occurring because the remember_token field is required by the Auth to be present in the users table. So you should add a remember_token field (likely a string field) in your users migration table and migrate it. Then, you should create a user, log in the user and then try logging out. Hopefully, doing this will solve your problem.
I guess you've run an update with composer recently and have upgraded the Laravel core. You'll need to perform a few steps to upgrade to the newest Laravel version as documented in the Laravel upgrade info here: http://laravel.com/docs/upgrade#upgrade-4.1.26
Laravel 4.1.26 introduces security improvements for "remember me"
cookies...change requires the addition of a new remember_token
column to your users (or equivalent) database table.
You'll also need to update your User class with these methods if you're using Eloquent:
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
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.