Home  >  Q&A  >  body text

In Laravel, how to implement database driver and provider authentication without using the elegant way

<p>The drivers supported by Laravel are "<strong>database</strong>" or "<strong>eloquent</strong>" to authorize the website. In the default <strong>config/auth.php</strong> we can see that it always states that the driver is eloquent. </p> <pre class="brush:php;toolbar:false;">``` /* |------------------------------------------------- ----------------------- | User Providers |------------------------------------------------- ----------------------- | | All authentication drivers have a user provider. This defines how the user's data is actually retrieved from the database or other storage mechanism. | | If you have multiple user tables or models, you can configure multiple sources representing each model/table. These sources can then be assigned to any additional authentication protection you define. | | Supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\Users::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], ```</pre> <p>Then we have a schema <strong>User</strong> associated with the table User for checking authentication. Therefore, we can use some of the <strong>auth</strong> methods: <strong>auth::check(), auth::atemp(), auth:login(),...</strong> If I don't use Model App\Models\Users::class, but use <strong>'driver' => 'database'</strong>, then how can I use some <strong>auth</strong> What about the function for authorization? </p>
P粉043566314P粉043566314390 days ago348

reply all(1)I'll reply

  • P粉781235689

    P粉7812356892023-08-29 00:01:31

    Just change the driver to database, you can easily comment out the eloquent part and uncomment the driver database part and you can use auth() normally as before. Laravel's auth functionality is plug and play.

    'users' => [
        'driver' => 'database',
        'table' => 'users', //或者您用于用户的任何表。
    ]

    You can design your signIn method in AuthController as follows:

    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('登录详细信息无效');
        }

    It will work in both eloquent and database drivers.

    reply
    0
  • Cancelreply