简体   繁体   English

如何在 Laravel Eloquent 中使用变量作为属性名称

[英]How to use variables as attribute name in Laravel Eloquent

Is there anyway to use variables in eloquent Example:无论如何在 eloquent 示例中使用变量:

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我正在尝试检查用户的级别是否与课程的 ID 相同或更高

I think your main question here is: Can you use a variable as attribute name on a laravel Eloquent model.我认为您的主要问题是:您能否在 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.如果您将一些代码移动到用户 Model 您的 controller 会变得更整洁一些。

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

then your Controller becomes cleaner:然后你的 Controller 变得更干净:

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"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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