ymoya
ymoya

Reputation: 11

laravel 5.7 Relationships belongsto hasmany error

I'm new to laravel, I'm beginning with laravel 5.7. I have two model.

Modelo categoria:

class categoria extends Model
{
    public function indicadores()
    {
        return $this->hasMany('App\Indicador');
    }
}

Modelo Indicador:

class Indicador extends Model

    {
        public function categoria()
        {
            return $this->belongsTo('App\categoria');
        }
    }

In the controller, I look for all Indicador

class IndicadorController extends Controller {

       public function index() {       
         $indicadores = DB::table('indicadors');
        return view('indicador.index', ['indicadores' => $indicadores]);
    }

When I try to show the category to which the indicador belongs,

 <tbody>
                    @foreach ($indicadores as $indicador)
                    <tr>
                        <td>{{ $indicador->categoria->nombre }}</td>
                    </tr>
                    @endforeach    
                </tbody>

I get the following error

Undefined property: stdClass::$categoria (View:resources\views\indicador\index.blade.php)

And I don't understand why. Thanks in advance

Upvotes: 1

Views: 211

Answers (2)

Elisha Senoo
Elisha Senoo

Reputation: 3594

Use Eloquent instead of the query builder:

class IndicadorController extends Controller {

    public function index() {       
        $indicadores = Indicador::all();
        return view('indicador.index', ['indicadores' => $indicadores]);
    }

}

Upvotes: 0

Angad Dubey
Angad Dubey

Reputation: 5452

Using the DB facade returns an instance of Illuminate\Database\Query\Builder

so the relationship will not be accessible.

You instead want an Eloquent model instance which you can use the model directly:

use App\Indicador;
...
$indicadores = Indicador::all();

or as @Chris suggests, eager load:

$indicadores = Indicador::with('categoria')->get();

Upvotes: 1

Related Questions