Home > Software design >  Not using eloquent . How using providers auth with driver = database in laravel
Not using eloquent . How using providers auth with driver = database in laravel

Time:09-14

Laravel supported driver "database" or "eloquent" to authorize website . In default config/auth.php we can see it alway declare drive is eloquent.

    ``` 
       /*
        |--------------------------------------------------------------------------
        | 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\Models\Users::class,
            ],
    
            // 'users' => [
            //     'driver' => 'database',
            //     'table' => 'users',
            // ],
        ],
    ```

Then we have a mode User refer with table User to check authentication. So we can using some method of auth : auth::check(),auth::atemp(),auth:login(),... If I dont using Model App\Models\Users::class,. I using 'driver' => 'database'. How i can auhorize by using some function of auth ,

CodePudding user response:

Just change the drive to database, you can easily comment out the eloquent part and uncomment the driver database section, you can use auth() normally as you were using before. Laravel's auth works out of the box.

'users' => [
    'driver' => 'database',
    'table' => 'users', //Or whatever table you are using for users.
]

You can design your signIn method in your AuthController, like bellow:

public function signIn(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            return redirect('/');
        }

        return redirect('login')->withErrors('Login details are invalid');
    }

It will work in both eloquent and database drivers.

  • Related