Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

332
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda