chahal's avatar

Different tables for User

Hi guys,

I usually prefer going with a single users table and adding user_type to it. But the users I have for my SPA and a. mobile application are completely different and I don't want to create a mess out of it.

Should I consider, making 2 different tables for both types of users? Both types of users will be authenticated using sanctum and a bearer token needs to be generated for both of them.

I am looking for making different guards in this case.

Best practices to make this work with ease??

0 likes
3 replies
LaryAI's avatar
Level 58

Yes, it is a good idea to create separate tables for different types of users. This will help you to keep your code clean and organized. You can create two tables, one for SPA users and another for mobile application users. You can use Laravel's built-in authentication system to authenticate both types of users.

To create separate guards for both types of users, you can define them in your config/auth.php file. Here's an example:

'guards' => [
    'spa' => [
        'driver' => 'session',
        'provider' => 'spa_users',
    ],

    'mobile' => [
        'driver' => 'session',
        'provider' => 'mobile_users',
    ],
],

In this example, we have defined two guards, one for SPA users and another for mobile application users. We have also specified the providers for each guard. You can define the providers in the config/auth.php file as well.

'providers' => [
    'spa_users' => [
        'driver' => 'eloquent',
        'model' => App\Models\SpaUser::class,
    ],

    'mobile_users' => [
        'driver' => 'eloquent',
        'model' => App\Models\MobileUser::class,
    ],
],

In this example, we have defined two providers, one for SPA users and another for mobile application users. We have also specified the models for each provider.

Once you have defined the guards and providers, you can use them in your controllers and routes. Here's an example:

Route::middleware('auth:spa')->get('/spa', function () {
    // Only authenticated SPA users can access this route
});

Route::middleware('auth:mobile')->get('/mobile', function () {
    // Only authenticated mobile application users can access this route
});

In this example, we have defined two routes, one for SPA users and another for mobile application users. We have also specified the guards for each route using the auth middleware.

I hope this helps!

martinbean's avatar

@chahal I fail to see why you would have a different “type” of use just because you have a SPA and a mobile application?

Your application has users. You’d use something like Sanctum or Passport to be able to obtain API tokens to interact with your app as that user.

chahal's avatar

@martinbean Hi, I think you took it wrong. SPA and mobile application is just for ref. Both type of users are completely different and would be complex to keep them in same table.

Please or to participate in this conversation.