laravel - redirecting three different user types/r

2019-06-14 20:22发布

问题:

I use laravel 5.4 and I want to redirect these three different types of users to different pages

Schema


Types
+-------+-------------+
| id    | name        |
+-------+-------------+
| 1     | Super Admin |
| 2     | Admin       |
| 3     | Cashier     |
+-------+-------------+

Users    
+-------+---------+-------------+
| id    | type_id | name        |
+-------+---------+-------------+
| 1     | 1       | Super Admin |
| 2     | 2       | Admin       |
| 3     | 3       | Cashier     |
+-------+---------+-------------+

i write code like this

use Auth;

public function redirectTo()
{
    $superAdmin = Auth::user()->type_id = 1;
    $admin = Auth::user()->type_id = 2;
    $cashier = Auth::user()->type_id = 3;

    if ($superAdmin) {
        return '/superAdmin/home';
    }
    elseif ($admin) {
        return '/admin/home';
    }
    elseif ($cashier) {
        return '/cashier/home';
    }
}

but it always redirects to '/superAdmin/home', can someone tell what my fault is?

回答1:

use Auth;

public function redirectTo()
{
    $superAdmin = 1;
    $admin  = 2;
    $cashier = 3;

    if ($superAdmin == Auth::user()->type_id) {
        return '/superAdmin/home';
    }
    elseif ($admin == Auth::user()->type_id) {
        return '/admin/home';
    }
    elseif ($cashier == Auth::user()->type_id) {
        return '/cashier/home';
    }
}

Try this



回答2:

You need to compare type_id with some value, for example:

public function redirectTo()
{
    if (auth()->user()->type_id === 1) {
        return '/superAdmin/home';
    } elseif (auth()->user()->type_id === 2) {
        return '/admin/home';
    } elseif (auth()->user()->type_id === 3) {
        return '/cashier/home';
    }
}

Also, it's a good idea to use constants instead of integers like 1, 2 and 3.



回答3:

You need to be able to have a full back incase the users tupe_id is null just in case as a fall back.

use Auth;

public function redirectTo()
{
    if(Auth::user()->type_id === null){
        return '/404'; // IF you dont have a type id
    } esleif(Auth::user()->type_id === 1){
        return '/superAdmin/home';
    } esleif(Auth::user()->type_id === 2){
        return '/admin/home';
    } esleif(Auth::user()->type_id === 3){
        return '/cashier/home';
    }
}


回答4:

Try to understand what you have written in your code You are assigning 1 to $supseadmin as well as auth::User()->type_id

Then in the if condition you are checking if($superadmin){}

means if(1){} Then this type of if condition just check if the data exists then it goes in to the if statements body where you are returning To super admin