How to make two types of users in Laravel

2019-05-24 21:53发布

问题:

I want to ask how to make two types of users in laravel. I have two tables, one for the customer and one for the client and my question is how to make that difference. Do I have to make two different models or to use model User and make some functions in middleware?

Thank you.

回答1:

If you're looking for the simpliest solution, you can add role column to users table. Then you can check if user is a client or a customer globally with:

if (auth()->user()->role === 1) {
    // It's a client.
}

You can add some helper methods to check if user is a client or a customer:

public function isClient()
{
    return auth()->user() && auth()->user()->role === 1;
}

To open the part of the website for client only you should use route groups and middleware.



回答2:

I've run into the same situation and I've resolved it by using a package that handles multi-authentication: Check out this package:

  • https://packagist.org/packages/hesto/multi-auth

There are also a blog post about this situation:

  • http://santo.sh/multi-login-for-laravel-5-3/

and of course more StackOverflow questions:

  • Using multiple Auth in Laravel 5.3?
  • Multiple Authentication in Laravel 5.3