4

Estoy intentado pasar una variable que recibo, entonces comparando con la variable me dice que la variable no está definida:

Post::where('post_id', $id)
->with(['users' => function($query){
    $query->with(['user_comments' => function($q){
        $q->where('year_comment', '=', $year);
    }]);
}])->first();

Undefined variable: year

Nota: la variable llega correctamente.

2 respuestas 2

2

Creo que la respuesta de Aprendiz no es del todo correcta teniendo en cuenta que hay un doble contexto por dos funciones anónimas anidadas, por lo cual habría que utilizar use dos veces, en cada función:

Post::where('post_id', $id)
    ->with(['users' => function($query) use ($year) {
        $query->with(['user_comments' => function ($q) use ($year) {
            $q->where('year_comment', '=', $year);
        }]);
    }])->first();
2
  • Totalmente de acuerdo + 1
    – BetaM
    el 3 ago. 2019 a las 15:41
  • GRACIAS !!! el 3 ago. 2019 a las 15:42
1

Estas usando una función anónima, por lo tanto deberás hacer uso de use para pasarla y que exista dentro del contexto de la función así:

Post::where('post_id', $id)
->with(['users' => function($query){
    $query->with(['user_comments' => function($q) use($year){
        $q->where('year_comment', '=', $year);
    }]);
}])->first();

Estructura de la función anónima

$variable = 12;

$mensaje = function() use($variable){
    echo $variable;
};

$mensaje();

Lo cual va a dar como resultado:

12

Referencias

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.