Error searching for Description in another related table

Asked

Viewed 23 times

0

Error:

Trying to get property of non-object

View

@foreach ($titulos as $titulo)
    <tr>
        <td>{{ $titulo->id }}</td>
        <td>{{ $titulo->titulo_tipos->description }}</td> //ERRO NESSA LINHA
        <td>{{ $titulo->cliente->nome }}</td>
        <td>{{ $titulo->devedor->nome }}</td>
        <td>{{ $titulo->Valor }}</td>
    </tr>
@endforeach

Models Titulo

class Titulo extends Model
{
     public function titulo_tipos()
     {
         return $this->belongsTo('App\Models\TituloTipo');
     }
}

Model Title Type

class TituloTipo extends Model
{
    public function titulo()
    {
        return $this->hasMany('App\Models\Titulo');
    }
}

Migration

Schema::create('titulos', function (Blueprint $table) {
    $table->increments('id');

    $table->integer('tipo_id')->unsigned();
    $table->foreign('tipo_id')->references('id')->on('titulo_tipos');

    $table->integer('cliente_id')->unsigned();
    $table->foreign('cliente_id')->references('id')->on('clientes');

    $table->integer('devedor_id')->unsigned();
    $table->foreign('devedor_id')->references('id')->on('devedors');

    $table->date('vencimento_titulo')->nullable();
    $table->string('status')->default('pendente');
    $table->decimal('Valor')->nullable();

    $table->timestamps();
});
  • In the Title Model refer to Foreign key type_id Return $this->belongsTo('App Models Titulotipo', 'type_id');

  • Perfect, worked!

1 answer

1


Your mistake is in

return $this->belongsTo('App\Models\TituloTipo');

When using the belongsTo with only one parameter you assume that the Foreign key will be the name of the related model accompanied by _id, in the titulotipo_id case, but this field does not exist in your model. You must then manually reference which foreignkey field will reference the Titulotipo table. Applying the correction would be as follows:

$this->belongsTo('App\Models\TituloTipo', 'tipo_id');

This and other explanations you can find in Documentação do Laravel.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.