Checking for Roles & Permissions in zizaco/entrust laravel package - laravel

I'm using zizaco/entrust package in my laravel project beside multi Auth package name Hesto/multi-auth
Our project on laravel 5.4,
i get below error when i want to get current logged in users' role and permissions with this method:
Entrust::hasRole('role-name'); OR Auth::user()->hasRole('role-name');
But I can access users' Role with this method for example :
$user = User::find($userid);
dd($user->hasRole('admin')); // Return true
i followed exactly installation instruction but i get below error :
`Non-static method Zizaco\Entrust\Entrust::hasRole() should not be called statically`
How can i solve my problem,
Thanks in advance

In this error message you have answer to your problem:
Non-static method Zizaco\Entrust\Entrust::hasRole() should not be called statically
You called this method hasRole() statically, but this method is non static. It means that you need to create object of this class, but you instead that used a class.
In the example that you gave:
$user = User::find($userid);
dd($user->hasRole('admin')); // Return true
you create an object of class User, and class User (I think) implements class Entrust:
$user = User::find($userid);
$user is an object and it`s not static, you can use hasRole().
In other words, to use method hasRole() (literally - is someone has a role?) you need this someone:
$user->hasRole('admin') // Is this user has role `admin`?
Hope, I explained it. Sorry about my English (I'm just studying).

In your User.php file add EntrustUserTrait like
<?php
namespace App;
//...
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Authenticatable
{
use Notifiable, EntrustUserTrait;
//...

Related

Correct way to pass model instance from middleware to controller?

If I have a middleware that fetches a related model from an authenticated User (ie: Info model), checking stuff and throwing error if an inconsistency is found in User's Info, otherwise I want to use that same Info in my controller without making the same query again.
I know I can $request->request->add(['info' => $info]) and then call it as request('info') in my controller, but it doesn't seems to be the best way since it's giving me a huge headache when combined with Livewire resulting in weird and unexpected behavior.
So, what is the correct way to do this?
You can refer to this documentation. Laravel 8 Authentication
So what it says basically is that once you are authenticated, you can always use Auth facade anywhere from your code and get the Info model associated to it (Assuming you have setup the eloquent relationship between your User & Info models)
e.g.
use Illuminate\Support\Facades\Auth;
// MyController.php
public function index(Request $request)
{
// Let's say Info model has address column
$address = Auth::user()->info->address;
}
Your User model should have relationship with Info Model like this, well then again assuming Info class has one to one relationship with your User class
Source: Laravel 8 Eloquent
class User extends Authenticatable
{
public function info()
{
return $this->hasOne(\App\Models\Info::class);
}
}

Laravel sanctum custom model

I'm using Laravel sanctum to authenticate my API, and I wanted to customize personal access token model so I did the following:
I created new model named PersonalAccessToken in App namespace.
I override model used in sanctum to be my new model by adding this line to my AppServiceProvider boot() method.
Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);
but when I create a token it works fine and insert it into DB but this line throw exception
return new NewAccessToken($token, $token->id.'|'.$plainTextToken);
and that's because it's type hinted to be an instance of Laravel\Sanctum\PersonalAccessToken
how can I fix that
If you are not extending the default PersonalAccessToken that maybe your issue.
Instead of extending Model extend use Laravel\Sanctum\PersonalAccessToken
use Laravel\Sanctum\PersonalAccessToken as Model;
class CustomPersonalAccessToken extends Model
{
// Add you customisation here
}

Saving an object into the session or cookie

I'm using Instagram API library to connect user to Instagram profile and then do smth with it. So, as Instagram API wiki says:
Once you have initialized the InstagramAPI class, you must login to an account.
$ig = new \InstagramAPI\Instagram();
$ig->login($username, $password); // Will resume if a previous session exists.
I have initialized InstagramAPI class and then I called $ig->login('username', 'password');. But I have to call it in every function where I need to work with Instagram.
So how could I save this object $ig for using it in the future in other controllers without calling login() any more? Can I save $ig object into the session or cookie file?
P.S. I think saving into the session is not safe way to solve the issue.
UPD: I was trying to save $ig object into the session, however the size is large and session become stop working as well.
Regarding the register method you asked in the comments section, all you need to create a new service provider class in your app\providers directory and declare the register method in there for example:
namespace App\Providers;
use InstagramAPI\Instagram;
use Illuminate\Support\ServiceProvider;
class InstagramServiceProvider extends ServiceProvider
{
public function register()
{
// Use singleton because, always you need the same instance
$this->app->singleton(Instagram::class, function ($app) {
return new Instagram();
});
}
}
Then, add your newly created InstagramServiceProvider class in providers array inside the config/app.php file for example:
'providers' => [
// Other ...
App\Providers\InstagramServiceProvider::class,
]
Now on, in any controller class, whenever you need the Instagram instance, all you need to call the App::make('InstagramAPI\Instagram') or simply call the global function app('InstagramAPI\Instagram') or even you can typehint the class in any method/constructor etc. Some examples:
$ig = App::make('InstagramAPI\Instagram');
$ig = App::make(Instagram::class); // if has use statement at the top fo the class
$ig = app('...');
In a class method as a dependency:
public function someMethod(Instagram $ig)
{
// You can use $ig here
}
Hope this helps but read the documentation properly, there will get everything documented.

Laravel 5 Unable to access currently logged in user id from custom helper

In AppServiceProvider, I called a function from a custom helper as follows:
public function boot()
{
View::share('tree', customhelper::generateSiteTree(0));
}
The custom helper file is calling the database function as below:
$children = UserPermission::getLeftNavByUserId($startAt);
In the custom helper function, I want to pass the current logged in user ID however, dd(Auth::user()) is returning null.
How can I pass the Auth::user()->id with the method
getLeftNavByUserId($startAt, Auth::user()->id);
The variable (or Facade) isn't available yet. One way to solve this is by using a view composer.
View::composer('my.view.with.children', function(View $view){
$view->with('children', UserPermission::getLeftNavByUserId($startAt, Auth::id()));
});
Ofcourse you need to add a check if the user is logged in or not etc.
Custom helper function will be initialized in application instance before the Auth middleware therfore it will always be null, if you want to use the auth user bind it from middlware instead.

Laravel 5.2, friendship model, how to add correctly in the User model?

I try to implement this solution to Laravel 5.2,
I did all installation steps, but I can't get it to work, and for example I want to use $user->getFriends();, I can use it directly from view or only from constructor?
And where I must setup a model, on User.php or I can do it in Friend.php?
You want to add the Friendable trait to your User model.
use Hootlex\Friendships\Traits\Friendable;
class User extends Model
{
use Friendable;
...
}
Then, if you've installed everything and migrated the database, you can access friendships like below:
$user = new User::find(1);
$recipient = new User::find(2);
// both `$user` and `$recipient` are instances of your `User` model
// no `Friend` model needed.
$user->befriend($recipient);
// now `$user` has just friended `$recipient`
// you should be able to access all the methods provided by the trait.

Resources