Laravel 5.3 Trying to get property of non-object

4

Good morning! I followed what is said in this tutorial to fill values in a view: link

And I did the same scheme on my controller:

public function select_cursos_disciplinas()
{
    $cursos = DB::table('select * from cursos');
    $disciplinas = DB::table('select * from disciplinas');
    return view('cadastros.disciplinas_curso', ['cursos' => $cursos, 'disciplinas' => $disciplinas]);
}

In my view it looks like this:

<select class="form-control">
    <option disabled selected> --- </option>    
    @if ($cursos)
        @foreach ($cursos as $curso)
            <option> {{ $curso->nome }} </option>
        @endforeach
    @endif
</select>

However, it is giving the error "Trying to get property of non-object". I already researched but did not find the solution for what I need, because the solution was for only one value, but in my case I want several values even.

What should I do to make my select complete? Thanks

    
asked by anonymous 03.11.2016 / 12:58

2 answers

3

It turns out that your method is not loading the data into the object. For this you need to apply the get() method to the end of the table method.

As in the example below:

public function select_cursos_disciplinas()
{
    $cursos = DB::table('select * from cursos')->get();
    $disciplinas = DB::table('select * from disciplinas')->get();
    return view('cadastros.disciplinas_curso')
           ->with('cursos', $cursos)
           ->with('disciplinas', $disciplinas);
}

Your foreach in the view is right.

    
03.11.2016 / 13:07
2

I think it's best to use Query Builder of Eloquent . Please try the following.

public function select_cursos_disciplinas()
{
    $curso = new Curso();
    $cursos = $curso->all();

    $disciplina = new Disciplina();
    $disciplinas = $disciplina->all();

    return view('cadastros.disciplinas_curso', 
        [
            'cursos' => $cursos, 
            'disciplinas' => $disciplinas
        ]
    );
}
    
03.11.2016 / 13:23