Laravel Spatie/Laravel-Permission Failed to fetch role data - laravel

what im trying to do is fetcing role data from single actions controller and got error messege when i test it out from postman. "message": "Call to undefined method App\Models\User::auth()", for anyone can give me hint or solution to fix this problems will highly appriciate. for further information im using jwt for auth, api as the guard.
so let me show you my code.
Controller:
<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
class RoleController extends Controller
{
public function __invoke()
{
return User::auth()->user()->getRoleNames();
}
}
Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable, HasRoles;
protected $guard_name = "api";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getJWTIdentifier(){
return $this->getKey();
}
public function getJWTCustomClaims(){
return [];
}
}
routes:
//group route with prefix "admin"
Route::prefix('admin')->group(function () {
//route login
Route::post('/login', [App\Http\Controllers\Api\Admin\LoginController::class, 'index']);
//group route with middleware "auth"
Route::group(['middleware' => 'auth:api'], function() {
//data user
Route::get('/user', [App\Http\Controllers\Api\Admin\LoginController::class, 'getUser']);
//refresh token JWT
Route::get('/refresh', [App\Http\Controllers\Api\Admin\LoginController::class, 'refreshToken']);
//logout
Route::post('/logout', [App\Http\Controllers\Api\Admin\LoginController::class, 'logout']);
Route::prefix('authorization')->group(function () {
Route::get('/roles', RoleController::class);// not working
});
});
});

There are few ways you can try for getting those roles:
shows all the role names
Auth::user()->roles
$roles = $user->getRoleNames(); // Returns a collection
check user has specific role
Auth::user()->hasRole('admin')
check user has any roles
Auth::user()->hasAnyRole(['super_admin', 'vendor'])
For other usage take a look at the site:
Spatie roles and permission info

Related

Laravel Relationship Null

I am having an issue following a tutorial on YouTube about relationships.
I have replicated this code from the tutorial and I keep getting errors.
I've tried changing the controller code from auth() to app etc.
Also, I've tried re-running migrations:fresh etc and nothing.
User Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Notifiable, Billable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the Instance associated with the user.
*
* #return HasMany
*/
public function instance()
{
return $this->hasMany(Instance::class);
}
}
Instance Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Instance extends Model
{
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
class SyncController extends Controller
{
public function successful()
{
return auth()->user()->instance()->create(['name' => 'test']);
}
}
Error
Call to a member function instance() on null {"exception":"[object] (Error(code: 0): Call to a member function instance() on null at /home/#/cc.#.io/app/Http/Controllers/SyncController.php:14)
[stacktrace]
Edit:
Route::middleware(['auth'])->group(function() {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::get('/subscribe', SyncController::class);
});
Check if your route is guarded by auth middleware. If not you can add that in order to fix. You might use Route group like following -
Route::group(['middleware' => ['auth']], function () {
Route::resource('your_url', 'YourController');
// Or whatever route you want to add...
});
This is because the auth()->user is getting null and it will be necessary to check if the value was actually received after the call was made.

403 user does not have any necessary access rights in laravel usercontroller laratrust

I am trying to get all user in my table but I get an error 403 user does not have the necessary rights. I am using laratrust and vuejs. I have already logged in as a superadministrator. This is my controller class
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('role:user|superadministrator');
}
public function index()
{
return view('user.index');
}
public function getusers(){
$theUser = Auth::user();
if ($theUser->hasRole('superadministrator')) {
return $users;
}
}
}
My api route
Route::get('/allusers','UserController#getusers');
I have tried to go through the documentation but no success.Kindly help me solve this issue
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laratrust\Traits\LaratrustUserTrait;
class User extends Authenticatable
{
use LaratrustUserTrait;
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
What about if you try this:
public function getusers(Request $request){
$theUser = $request->user('api');
if ($theUser->hasRole('superadministrator')) {
return $users;
}
}

Call to a member function hasVerifiedEmail() on null

I am using Laravel 7 and I am trying to verify my email I have followed all the steps mentioned in the documentation but I am still getting this error please me to resolve this error, Thanks
I added the user model code here
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'password', 'permissions'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
here is web.php
Auth::routes(['verify'=> true]);
Route::prefix('student')->middleware(['auth', 'verified'])->group(function () {
Route::get('dashboard', 'StudentController#dashboard');
});
The $request is sending a null value because you need to be logged in (authenticated) in order to get an instance of the $user
Make sure you have a middleware of auth on your route
Assigning Middleware To Routes:
Route::get('admin/profile', function () {
//
})->middleware('auth');
or Middleware Groups:
Route::group(['middleware' => ['auth']], function () {
Route::get('admin/profile', function(){
//your function here
});
});
Laravel Official Doc
only users logged could acheave the function hasVerifiedEmail() , because of that you get the response : Call to a member function hasVerifiedEmail() on null ,
to fix that issue you have to customise show function in VerificationController.php
public function show(Request $request)
{
//login user
if (auth()->user())
{
return $request->user()->hasVerifiedEmail()
? redirect($this->redirectPath())
: view('auth.verify');
}
//guest
else
{
return $request->user()
? redirect($this->redirectPath())
: redirect('/login');
}
}

laravel multi authentication using admin roles

I've two types of users in my application. 'admins' & 'frontend users'. 'admin' has roles. i want redirect admins according to their roles. i've done the multiauth system but don't know how to redirect admins according to their roles.
here is admin model ->
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use Notifiable;
protected $guard = 'admin';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
// public function post(){
// return $this->hasOne('App\Post');
// }
public function role()
{
return $this->belongsTo('App\Role');
}
}
here is role model ->
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function admins()
{
return $this->hasMany('App\Admin');
}
}
here is the login controller for admins ->
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
use App\Admin;
use App\Role;
class BackendLoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest:admin', ['except' => ['logout']]);
}
public function showLoginForm()
{
return view('backEnd.backEnd-login');
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember))
{
return redirect()->intended(route('dashboard'));
}
return redirect()->back()->withInput($request->only('email', 'remember'));
}
public function logout()
{
Auth::guard('admin')->logout();
return redirect('/');
}
}
here is the login controller for users ->
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'userLogout']]);
}
public function userLogout()
{
Auth::guard('web')->logout();
return redirect('/');
}
}
routes ->
Route::get('/backend-login', 'Auth\BackendLoginController#showLoginForm')->name('backend.login');
Route::post('/backend-login', 'Auth\BackendLoginController#login')->name('backend.login.submit');
Route::get('/dashboard', 'BEController#index')->name('dashboard');
Route::get('/logout', 'Auth\BackendLoginController#logout')->name('backend.logout');
i've made guards and done the multiauth but can't set the role base system natively

Method roles not found in laravel Auth

I keep getting the method not found error when I'm trying to assign a role to the user in the user registration section.
The following is the code that I am using in the AuthController
namespace App\Http\Controllers\Auth;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthController extends Controller
{
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
])->get();
$user->roles()->sync([2]);
return $user;
}
}
following is my User model
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\HasRole;
use App\Role;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $fillable = [
'first_name','last_name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
I'm not sure why this is happening. I think maybe it's not importing the User model properly, or I'm missing something. I'm new to laravel, so any help will be welcome.
To create a model simply use the following:
$user = User::create($attributes)
Notice that I did not call get() afterwords. get() will perform a query returning a Collection. I'm not sure what your Role model looks like, but it should work properly now.

Resources