Simple user role authority in Laravel Api with passport

Gary Roberts
1 min readMay 14, 2021

Basic implementation that can handle the permission of specific controller methods if the current user type does not have the authority

(1) Make the migration. Below is an example with staffType representing field to hold user role

<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;
class CreateStaffTable extends Migration{public function up(){Schema::create('staff', function (Blueprint $table) { $table->id(); $table->string('email',255); $table->enum('staffType', ['DOCTOR','RECEPTIONIST','ADMIN']); $table->string('fname',50); $table->string('lname',50); $table->timestamps(); });
}
public function down(){ Schema::dropIfExists('staff');}}

(2) Make a function in auth model to handle role based authority

public static function check_authority($levels){$response=NULL;$user_auth=Auth::user();if(!in_array($user_auth->staffType,$levels)){    return false; //user not authorized}else{     return true; //user authorized so go ahead with query}}

NB: Please Import “use Illuminate\Support\Facades\Auth;” to access laravel auth

(3) Implementation of function at the top of controller methods to check before endpoint fires off queries. You are able to pass an array of user levels incase a route has to be accessed by more than one user type

$staff_auth=Auth::user(); //gets current userif(!$staff_auth::check_authority(['RECEPTIONIST','DOCTOR','ADMIN'])){ 
return $response = ['message' =>"user not authorized"];
}
else
{
return $response = ['message' =>"Hey you have access to this "];
}

Thats all. Thank you

--

--

Gary Roberts

I am a self driven software engineer who has a passion for web and mobile development. I have won multiple awards relating to computer programming.