如何在 laravel 中为我的购物项目创建 cms 用户类型和常规配置文件

how to create to type of user for cms and regular profile for my shopping project in laravel

我是 Laravel 的新手,我使用 5.8 版本 我试图创建一个购物网站,其中有两种类型的 AUTH,一种用于 cms,一种用于用户。用户可以从我的网站购买商品。为此,我需要将两种类型的登录分开,一种是 cms 管理员登录,另一种是用户登录。我想知道我该怎么做。谁能帮我。 对于客户资料,我使用 web.php 文件和用户路由组,我分享如下:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', [
    'uses' => 'ProductController@getIndex',
    'as' => 'product.index'
]);

Route::get('/add-to-cart/{id}', [
    'uses' => 'ProductController@getAddToCart',
    'as' => 'product.addToCart'
]);

Route::get('/shopping-cart', [
    'uses' => 'ProductController@getCart',
    'as' => 'product.shoppingCart'
]);

Route::get('/checkout', [
    'uses' => 'ProductController@getCheckout',
    'as' => 'checkout'
]);

Route::post('/checkout', [
    'uses' => 'ProductController@postCheckout',
    'as' => 'checkout'
]);

Route::group(['prefix' => 'user'], function (){

    Route::group(['middleware' => 'guest'], function (){
        Route::get('/signup', [
            'uses' => 'UserController@getSignup',
            'as' => 'user.signup',
        ]);

        Route::post('/signup', [
            'uses' => 'UserController@postSignup',
            'as' => 'user.signup',
        ]);

        Route::get('/signin', [
            'uses' => 'UserController@getSignin',
            'as' => 'user.signin',
        ]);

        Route::post('/signin', [
            'uses' => 'UserController@postSignin',
            'as' => 'user.signin',
        ]);
    });

    Route::group(['middleware' => 'auth'], function (){
        Route::get('/profile', [
            'uses' => 'UserController@getProfile',
            'as' => 'user.profile',
        ]);

        Route::get('/logout', [
            'uses' => 'UserController@getLogout',
            'as' => 'user.logout',
        ]);
    });
});

我需要 cms 的另一个 AUTH,以便管理员可以上传待售商品

您不需要为不同类型的用户使用单独的 login 逻辑。您可以通过修改当前用户 table 来集中此逻辑。您需要做的就是将角色分配给用户。例如,在您的用户 table 上创建 role 属性,您可以在其中拥有两个不同的角色:

  1. 管理员
  2. 用户

现在,当您拥有其中两个角色时,您可以修改登录逻辑,将用户重定向到他们所属的页面。 Laravel 提供开箱即用的功能。您需要做的就是修改 Laravel 内置的 redirectIfAuthenticated 中间件。所以,你会得到这样的东西:

public function handle( $request, Closure $next, $guard = null ) {
        if ( Auth::guard( $guard )->check() ) { //check if user is authenthicated
            $user = Auth::user();
            switch ( $user->role ) {
                case 'admin':
                    return redirect( )->route('admin');
                    break;
                case 'user':
                    return redirect()->route('user');
                    break;
                default:
                    return redirect( '/' );
            }
        }
        return $next( $request );
    }

所以在这个例子中,我们将检查经过身份验证的用户的角色,以确定他应该被重定向到哪个页面。这是一个如何为用户处理不同角色的基本示例,但它应该能让您大致了解这些东西是如何工作的,并帮助您解决问题。您可以在 official documentantion 上阅读有关 Laravel 的内置身份验证系统的更多信息,您可以在其中找到更多处理逻辑功能的方法。希望这可以帮助你,并引导你朝着正确的方向前进。

创建一个管理模型,例如在 app\Models 中假设 Admin.php。转到您的 config\auth.php 文件并在 Authentication Guards 下制作类似这样的内容

/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/

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

    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
],

在供应商下的同一个文件中做这样的事情

 /*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

第二步 打开 app\Http\Middleware 文件夹下的 Authenticate.php 并使其看起来像这样

/**
 * Determine if the user is logged in to any of the given guards.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  array  $guards
 * @return void
 *
 * @throws \Illuminate\Auth\AuthenticationException
 */
protected function authenticate($request, array $guards)
{
    if (empty($guards)) {
        $guards = [null];
    }

    foreach ($guards as $guard)
    {
        if ($this->auth->guard($guard)->check()) {
            return $this->auth->shouldUse($guard);
        }
    }

    $guard = $guards[0];

    if ($guard == 'admin')
    {
        $request->path = 'url-to-admin-login-page';
    }
    else
    {
        $request->path = '';
    }

    throw new AuthenticationException(
        'Unauthenticated.', $guards, $this->redirectTo($request)
    );
}


/**
 * Get the path the user should be redirected to when they are not authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return string
 */
protected function redirectTo($request)
{
    if (! $request->expectsJson())
    {
        return route($request->path.'login');
        //return route('login');
    }
}

第三步 打开 app\Http\Middleware 文件夹中的 RedirectIfAuthenticated.php 并将其修改为

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @return mixed
 */
public function handle($request, Closure $next, $guard = null)
{
    switch ($guard)
    {
        case 'admin' :
        {
            if (Auth::guard($guard)->check())
            {
                return redirect('url-to-admin-home');//the url to admin home
            }
            break;
        }
        default :
        {
            if (Auth::guard($guard)->check())
            {
                return redirect('/home');
            }
            break;
        }
    }

    return $next($request);
}

第四步 最后,在所有管理控制器 classes 中,确保在它们的构造函数中添加一个防护 'auth:admin 来保护它们。例如

<?php

命名空间App\Http\Controllers;

使用App\Http\Controllers\控制器; 使用 App\Models\Admin;

class AdminController 扩展控制器 { /** * AdminController 构造函数。 */ public 函数 __construct() { $this->中间件('auth:admin'); }

public function index()
{
    return view('admin.home');
}

}

请注意:建议将原代码注释掉,不要删除。