Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Shady Hesham's avatar

is it secure to use laravel sanctum with spatie roles

I am building API with protecting the routes with Sanctum, as following and using the ability to give roles

Route::post('login', [AuthControllers_api::class, 'login']);
Route::group(['middleware' => 'auth:sanctum'], function () {
Route::resource('appointment', Appointment::class)->middleware('ability:Super-admin,Call-center');
});

and for login controller, I use the roles that come from spatie to store in sanctum abilities

public function login(Request $request)
  {    
    // Validate the form data
    $this->validate($request, [
        'phone_number'   => 'required|numeric',
        'password' => 'required',
        //'device_name' => 'required', for mobile app //need to be placed in token name
    ]);

    $user = User::where('phone_number', $request->input('phone_number'))->first();

    // Check password
    if(!$user || !Hash::check($request->input('password'), $user->password)) {
        return response([
            'message' => 'The phone number or passowrd is not correct'
        ], 401);
    }

    $roles = $user->getRoleNames()->toArray();

    $token = $user->createToken('mymobile_token', $roles)->plainTextToken;

    $response = [
        'user' => $user,
        'token' => $token
    ];

    return response($response, 201);
    
}

my question here is it enough to secure my API or do I need something else to implement?

0 likes
0 replies

Please or to participate in this conversation.