3

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

1 Answer 1

4

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"));
}
Sign up to request clarification or add additional context in comments.

1 Comment

actually I just gave my answer a review. The code could still be optimized a bit, look at updated version :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.