Using Laravel's 5.2 Authentication, the docs show that I can add more conditions to an authentication query like so:
Specifying Additional Conditions
If you wish, you also may 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":
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
In my case, I would like to set a condition which lives in another many-to-many Eloquent Model:
class Account extends Model
{
public function users() {
return $this->belongsToMany('App\User', 'account_users');
}
}
class User extends Model implements AuthenticatableContract
{
public function accounts() {
return $this->belongsToMany('App\Account', 'account_users');
}
}
There's an account id
which is passed though a middleware and I access it like this:
$request->account
How do I implement the new condition when it refers to a related model? I just don't know how to make use of the ORM relationship. Any help pointing in the right direction is much appreciated!
If you want to leverage Eloquent's relationship, you would probably need to add another condition inside of the 'if' control structure, unfortunately. Until your Auth::attempt() is done - there is no Auth::user() object and you need that object for ORM.
Therefore, you could do something like:
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Your extra conditions for accounts, just a couple of examples
if (count(Auth::user()->accounts) == 0) Auth::logout();
if (! Auth::user()->accounts()->active()->get()) Auth::logout();
}