Laravel 5 How to work with authentication on two d

2019-02-26 23:20发布

I created two different login forms with two different register forms and two different tables ,at the moment i can do the following

Login into table A(users)
Register into table A(users)
Register into table B(students)

But i can't logon on table B ,is like it is getting confused on which table to logon .I just modified the auth built-in functionality

Here is my code function for login under

     public function postLoginl(Request $request)
{
    $this->validate($request, [
        'learnerCell'=> 'required', 'password' => 'required',
    ]);

    $credentials = $this->getCredentialsl($request);

    if (Auth::attempt($credentials, $request->has('remember'))) {
        return redirect()->intended($this->redirectPath());
    }

    return redirect($this->loginPath())
        ->withInput($request->only('learnerCell', 'remember'))
        ->withErrors([
            'learnerCell' => $this->getFailedLoginMessage(),
        ]);
}

When I check on config/auth.php there is a script

 <?php

  return [
     'driver' => 'eloquent',
      'model' => App\User::class,
      'table' => 'users',
           'password' => [
    'email' => 'emails.password',
    'table' => 'password_resets',
    'expire' => 60,
  ],

];

of which i think is where the problem lies,because it does not have model to control the login it only references one model (User) and I have another one called (Learner).

2条回答
Ridiculous、
2楼-- · 2019-02-26 23:59

I assume you're using Laravel 5.1 - let me know if it's not true and I'll try to help you with other version as well.

Easiest way to do this is to store users in a single table with additional type flag. I understand that you want to have 2 different login processes and different credentials to be used for login. Once you have users in the same table the way to do that is:

class UserController {
    use AuthenticatesUsers;

    //use email for authentication
    public $username = 'email';

    protected function getCredentials(Request $request)
    {
        //allow only users with type=user
        return array_merge($request->only('email', 'password'), ['type' => 'user']);
    }
}

class LearnerController {
    use AuthenticatesUsers;

    //use phone for authentication
    public $username = 'phone';

    protected function getCredentials(Request $request)
    {
        //allow only users with type=learner
        return array_merge($request->only('phone', 'password'), ['type' => 'learner']);
    }
}
查看更多
男人必须洒脱
3楼-- · 2019-02-27 00:06

It can be done as below,

Under app\Http\Controllers\Student create AuthCotroller as below. This controller will handle student authentication.

<?php namespace App\Http\Controllers\Student;

use App\Http\Requests;
use App\Http\Controllers\Auth\AuthController as MainAuthController;

use Illuminate\Http\Request;

class AuthController extends MainAuthController {

    public $loginPath = '/student/login';

    public $redirectPath = '/student/dashboard';

    public $redirectAfterLogout = '/student/login';

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogin()
    {
        return view('student.login');
    }

    /**
     * Log the user out of the application.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogout()
    {
        $this->auth->logout();

        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }

    /** This method overrides Trait method. So, We can redirect Different Users to different destinations
     * Get the post register / login redirect path.
     *
     * @return string
     */
    public function redirectPath()
    {
        if (property_exists($this, 'redirectPath'))
        {
            return $this->redirectPath;
        }
        return property_exists($this, 'redirectTo') ? $this->redirectTo : '/student/dashboard';
    }
}

Now create following middleware,

<?php namespace App\Http\Middleware;

use Closure;

class ChangeUserToStudent
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        \Config::set('auth.table', 'students');
        \Config::set('auth.model', 'App\DB\Student');

        \Config::set('session.cookie', 'student_session');
        \Config::set('session.path', '/student/');

        return $next($request);
    }

}

Now in app/Http/kernel.php register above middleware with other middleware as below,

/**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
          .....
    'user.student' => 'App\Http\Middleware\ChangeUserToStudent',
          .....
        ];

now in routes.php create following routes group with middleware user.student,

<?php
// Protected Routes by auth and acl middleware
Route::group(['prefix' => 'student', 'namespace' => 'Student', 'middleware' => ['user.student']], function () {
    Route::get('login', [
        'as' => 'student.login',
        'uses' => 'AuthController@getLogin'
    ]);
    Route::get('logout', [
        'as' => 'student.logout',
        'uses' => 'AuthController@getLogout'
    ]);
    Route::post('login', 'AuthController@postLogin');
});
//Other student routes accessed only after login
Route::group(['prefix' => 'student', 'namespace' => 'Student', 'middleware' => ['user.student','auth']], function () {

    Route::get('dashboard', [
        'as'         => 'student.dashboard',
        'uses'       => 'DashboardController@index'
    ]);
]);

I hope you have already created Student model and students table which should essentially be at least same as a users table. Now, while you access route with student prefix, user.student middleware will jumps in and changes the authentication table to students and model to Student on the fly. You can even have different session for student as I have already shown.

Under view directory you can put all student related views under student directory. I assume you have separate login form for student which you should create under view\student directory.

This way you can completely separate student section from users section. I hope it helps.

查看更多
登录 后发表回答