Help with error Trying to get property of non-object Laravel

1

I have a relationship, where I try to get the name of a teacher, I can return the id of it, but when I try to return the name it gives me the message Trying to get property of non-object My code looks like this: Model Course.php

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Curso extends Model
{
    protected $fillable = [
        'professor_id',
        'nome'
    ];

    public function professor()
    {
        return $this->belongsTo(App\Professor);
    }
}

Model Teacher

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Professor extends Model
{
    protected $fillable = [
        'nome',
        'data_nascimento'
    ];

    public function cursos()
    {
        return $this->hasMany(App\Curso);
    }
}

CourseController

 */
public function index()
{
    $cursos = Curso::all();

    return view('curso.index', compact('cursos'));
}

And my index.blade.php

  @foreach($cursos as $value)
  <tr>
    <td>{{$value->id}}</td>
    <td>{{$value->nome}}</td>
    <td>{{ $value->professor->nome }}</td>
    <td>{{$value->created_at}}</td>

Here it gives the error, exactly in {{$ Value-> professors-> name}} My table is called professors by the way.

Can someone give me a light?

    
asked by anonymous 25.03.2018 / 23:37

1 answer

0

Always use loading in advance, because it only generates 2 SQL and thus there is no loss in performance , example of the modification:

public function index()
{
    $cursos = Curso::with('professor')->get();

    return view('curso.index', compact('cursos'));
}

other points have typos, example is not only App\Curso , or it is "App\Curso" or App\Curso::class , so I modified the two classes:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Curso extends Model
{
    protected $fillable = ['professor_id','nome'];

    public function professor()
    {
        return $this->belongsTo(\App\Professor::class);
    }
}

and

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Professor extends Model
{
    protected $fillable = ['nome','data_nascimento'];

    public function cursos()
    {
        return $this->hasMany(\App\Curso::class);
    }
}
    
25.03.2018 / 23:43