laravelsanctum

Change Users table with sanctum


Does Any one has and idea how to use applicants table (for example) instead of users table with laravel sanctum?

I tried adding this to auth.php but it didn't work

   'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'sanctum',
            'provider' => 'applicants',
        ],
    ],

'providers' => [
       'users' => [
           'driver' => 'eloquent',
           'model' => env('AUTH_MODEL', App\Models\User::class),
       ],

       'applicants' => [
           'driver' => 'eloquent',
           'model' => env('AUTH_MODEL', App\Models\API\Applicant::class),
       ],
   ],

Solution

  • You can't use env('AUTH_MODEL'.. for two different model class.

    Instead of your code try this one for applicants providers.

    'providers' => [
           'users' => [
               'driver' => 'eloquent',
               'model' => env('AUTH_MODEL', App\Models\User::class),
           ],
    
           'applicants' => [
               'driver' => 'eloquent',
               'model' => App\Models\API\Applicant::class,
           ],
       ],
    

    And in your guards add the providers name applicants not applicant.

    In laravel 11 default guard is users.So in case of custom-guard(in your case api which point to applicants providers) do this to authenticate users.

    if (Auth::guard('api')->attempt(['mobile' => $data['mobile'], 'password' => $data['password']])) 
    { 
      $applicant = Auth::guard('api')->user(); 
      $data['token'] = $applicant->createToken('API Token')->plainTextToken; 
    }
    else 
    {
    ....
    }
    

    Try this,it will work.

    In case of any other issue related to sanctum authentication You can take guide from this link.

    https://github.com/savanihd/Laravel-11-REST-API-using-Sanctum/blob/main/config/auth.php

    For more information about custom-guard configuration and how it will be accessed You can visit the official docs link given below..

    https://laravel.com/docs/11.x/authentication#accessing-specific-guard-instances