简体   繁体   中英

How to use variables as attribute name in Laravel Eloquent

Is there anyway to use variables in eloquent Example:

public function showLessons($skill)
    {
        $user = (\App\User::where('id', Auth::user()->getId())->first());
        $type = $user->type;
        if ($type === "student") {
            $bs = ($user->student_bronze_ . $skill);
            $ss = ($user->student_silver_ . $skill);
            $gs = ($user->student_gold_ . $skill);
        } elseif ($type === "school") {
            $bs = ($user->school_bronze_ . $skill);
            $ss = ($user->school_silver_ . $skill);
            $gs = ($user->school_gold_ . $skill);
        };
        return view('pages.lessons', compact("bs", "ss", "gs"));
    }

I am trying to check if the user's level is the same or higher than the lesson's id

I think your main question here is: Can you use a variable as attribute name on a laravel Eloquent model.

The answer is yes, you wrap it in curly braces {}

$user->{$type.'_'.$medal.'_'.$skill};

If you move some of your code to the User Model your controller get's a bit tidier.

// User.php
public function skill($medal, $skill) {
    $type = $this->type;    
    return $this->{$type.'_'.$medal.'_'.$skill};
}

then your Controller becomes cleaner:

public function showLessons($skill)
{
    $user = Auth::user();
    
    $bs = $user->skill('bronze', $skill);
    $ss = $user->skill('silver', $skill);
    $gs = $user->skill('gold', $skill);
    
    return view('pages.lessons', compact("bs", "ss", "gs"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM