yassine j
yassine j

Reputation: 515

Laravel Multiple auth error with condition

i need to specify redirection depent on which user is authentified. I add a column in the default laravel users table : "is_admin" with values "1" and "0"

In my controller i tried :

 if(Auth::user()->is_admin=1){
  return view('index');
 }
 else {
 return view('auth.login'); 
  };

But seem's my condition always true even if the auth has is_admin =0

How can i solve that problem ? Is there a better way to do this condition ? thanks

Upvotes: 0

Views: 294

Answers (2)

Yves Kipondo
Yves Kipondo

Reputation: 5603

To avoid this kind of issue you kind manage the way you specify value by creating const in you User Model. this allow you to have the same values which have same type all the time

class User extends Model
{
    const ADMIN_USER = "1";
    const REGULAR_USER = "0";

    public function is_admin()
    {
        return $this->attributes['is_admin'] == self::ADMIN_USER;
    }
}

when creating a non admin user you use this

User::create([
    // SET OTHER ATTRIBUTE
    'is_admin' => User::REGULAR_USER
]);

when creating the admin user you use this

User::create([
    // SET OTHER ATTRIBUTE
    'is_admin' => User::ADMIN_USER
]);

And when it come to check it in your view, you will have just to call the is_admin method on the Auth::user()->is_admin()

if(Auth::user()->is_admin()){
    // Your code goes here
} else {
    // And other codes goes here
}

Upvotes: 1

Jonathon
Jonathon

Reputation: 16283

Your problem is that you're assigning a value in your if statement, you've got a single = which assigns a value, rather than a double == (or triple ===) to compare values.

What's happening when you've only got a single = is that you're assigning the value 1 to whatever is before the = and that will evaluate to a "truthy" value meaning that the if will always be true no matter what and the else will never execute.

You should change it to this:

if (Auth::user()->is_admin == 1){ // Notice the two == here
    return view('index');
} else {
    return view('auth.login'); 
}

Notice that I have removed the semicolon at the end, it isn't necessary.

Upvotes: 2

Related Questions