Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

331
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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"));
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!