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

MikeMeijer's avatar

Relationship with one of two tables

Hi Guys,

I'm stumbling with a database relationship that I can't solve myself. I don't know if there's a good solution but I might overlook something.

My situation is that I have three tables called 'wholesalers', 'customers' and 'users'.

Wholesalers
    - ID
    - name
    
Customers
    - ID
    - name
    - wholesaler_id

Users
    - ID
    - username 
    - password
    - wholesaler_id OR customer_id ??

Scenario:

  • To login on my application, they have to be a user that I created for them.

  • When I add a user, they could be a customer or a wholesaler (not both).

  • There could be multiple users for a customer or wholesaler.

  • In the middleware that I use I want to know if the authenticated user is a customer or a wholesaler to determine if they can see a specific route.

I was thinking about a fourth table but didn't make it to a good working solution.

Does any of you guys have some tips or tricks how I can achieve the above scenario?

I appreciate every idea.

0 likes
3 replies
martinbean's avatar
Level 80

@Marknesse If you have “user types”, then you can just create middleware classes to verify if a user is a customer or a wholesaler, i.e.

class VerifyUserIsCustomer
{
    public function handle($request, Closure $next)
    {
        if ($request->user()->isCustomer()) {
            return $next($request);
        }

        abort(403, 'User is not a customer');
    }
}
// app/Http/Kernel.php

protected $routeMiddleware = [
    // Existing middleware classes
    'customer' => \App\Http\Middleware\VerifyUserIsCustomer::class,
    'wholesaler' => \App\Http\Middleware\VerifyUserIsWholesaler::class,
]

You’d then apply these middleware classes to your routes:

<?php

Route::middleware('auth', 'customer')->group(function () {
    // Customer-only routes
});

Route::middleware('auth', 'wholesaler')->group(function () {
    // Wholesaler-only routes
});
1 like
MikeMeijer's avatar

@martinbean

I knew how to setup the middleware but I didn't had the relationship for user types. After some Google research I ended up to use Polymorphic Relations.

My problem is solved, thanks for your answer.

martinbean's avatar

@Marknesse Yeah, if a user can belong to either a customer or a wholesaler then you could have a polymorphic relation for account, owner, or similar.

Please or to participate in this conversation.