2
votes

i have this two models:

class Opcion extends Model
{

    protected $table = 'opciones';

    public function pregunta(){ 
        return $this->belongsTo('Send\Pregunta', 'pregunta_id');
    }
}

class Pregunta extends Model
{

    protected $table = 'preguntas';

    public function opciones(){ 
        return $this->hasMany('Send\Opcion', 'pregunta_id');
    }
}

then in my controller:

 class GraficosController extends Controller
{
    public function getIndex(){
        $preguntas= \Send\Pregunta::where('encuesta_id','=',1)->get();
        $opciones= $preguntas->opciones();


        return view('graficos.grafico')->with(['preguntas'=>$preguntas,'opciones'=>$opciones]);
    }
}

im getting this error: Call to undefined method Illuminate\Database\Eloquent\Collection::opciones(), im trying to get all the "opciones" related with "preguntas"

1

1 Answers

2
votes

You're getting this error because the get() method returns a Collection object, which you can think of as an array of results. So the first element returned by your query would be $preguntas[0], and you could do this:

$opciones= $preguntas[0]->opciones();

But if you know that you're only going to get one result from your query, then you should use the first() method instead of get(). first() will return an instance of the first result from your query.

$preguntas= \Send\Pregunta::where('encuesta_id','=',1)->first();
$opciones= $preguntas->opciones(); // Now this will work