im having problem when im want to made multi role login, im also using SpatiePermission and implemented HasRoles on User model like this
namespace AppModels;
// use IlluminateContractsAuthMustVerifyEmail;
use LaravelSanctumHasApiTokens;
use SpatiePermissionTraitsHasRoles;
use IlluminateNotificationsNotifiable;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;
This is the api im tring to hit, so the i will need to pass bearer token to access /pendaftar
Route::middleware(['auth:sanctum', 'role:user'])->group(function () {
Route::post('pendaftar', [PendaftarController::class, 'store']);
});
i also had RoleMiddleware.php
with this followed function
public function handle(Request $request, Closure $next, ...$permissions)
{
foreach($permissions as $permission){
if (!$request->user()->hasPermission($permission)){
return redirect()->back();
}
}
return $next($request);
}
Inside kernel.php i had some configuration under the $middlewareGroup array, which is
'api' => [
// LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
IlluminateRoutingMiddlewareThrottleRequests::class.':api',
IlluminateRoutingMiddlewareSubstituteBindings::class,
LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
'throttle:api',
IlluminateRoutingMiddlewareSubstituteBindings::class,
'role' => AppHttpMiddlewareRoleMiddleware::class,
and some more configuration inside $middlewareAliases
protected $middlewareAliases = [
'auth' => IlluminateAuthMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'auth.session' => IlluminateSessionMiddlewareAuthenticateSession::class,
'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
'precognitive' => IlluminateFoundationHttpMiddlewareHandlePrecognitiveRequests::class,
'signed' => AppHttpMiddlewareValidateSignature::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
'auth' => AppHttpMiddlewareAuthenticate::class,
'role' => AppHttpMiddlewareRoleMiddleware::class,
];
But when i want to hit /pendaftar
there is error called on postman, (i also implemented accept = application/json)
"message": "Call to undefined method App\Models\User::hasPermission()",
I was expecting i can hit /pendaftar
without having those issue,
The token i pass it get from ”’/login“` api. and its return json response like this
{
"access_token": "5|thGZw3dQBPNWtvyMPsUPoUzo4Zgt4MjPWxNWMRHU322b0537",
"token_type": "Bearer",
"role": "user"
}