Posted: 23-08-2018

Laravel Authenticate Users with Additional Conditions

Laravel Authenticate Users with Additional Conditions

In Laravel the attempt method accepts an array of key / value pairs as its first argument.
The values in the array will be used to find the user in your database table.

So you can add extra conditions to the authentication query in addition to the user's e-mail and password.

For example, we may verify that user is marked as "active"

<?php 

namespace App\Http\Controllers;

use Auth;
use Illuminate\Routing\Controller;

class AuthController extends Controller {

    public function authenticate(Request $request)
    {
        $attempt = Auth::attempt([
            'email' => $request->get('email'), 
            'password' => $request->get('password'), 
            'active' => 1
        ]);

        if ($attempt) {
            return redirect()->intended('dashboard');
        }
    }

}


or users registered in a given shop:

<?php 

namespace App\Http\Controllers;

use Auth;
use Illuminate\Routing\Controller;

class AuthController extends Controller {

    public function authenticate(Request $request)
    {
        $attempt = Auth::attempt([
            'email' => $request->get('email'), 
            'password' => $request->get('password'), 
            'shop_id' => 3
        ]);

        if ($attempt) {
            return redirect()->intended('dashboard');
        }
    }

}