Laravel 5 Eloquent View Blade with Foreign Key?

Asked

Viewed 965 times

0

I get the following error:

Trying to get Property 'name' of non-object

I have a list of Suppliers and Payments, and I am using the following syntax to retrieve the Vendor name through the foreign payment key.

<td>{{$pagamento->fornecedor_id->nome}}</td>

Payments Table

public function up()
{
    Schema::create('pagamentos', function (Blueprint $table) {
        $table->increments('id');
        $table->date('data_pag');
        $table->decimal('valor');            
        $table->string('plano_contas', 20);
        $table->integer('fornecedor_id')->unsigned()->nullable();      
        $table->foreign('fornecedor_id')->references('id')->on('fornecedores')
            ->onUpdate('cascade')
            ->onDelete('set null');
        $table->timestamps();
    });
}

Suppliers Table

public function up()
{
    Schema::create('fornecedores', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nome', 55);
        $table->string('cnpj', 18)->unique();
        $table->string('endereco', 44);            
        $table->integer('numero');                
        $table->string('cep', 9);            
        $table->string('complemento', 44)->nullable();            
        $table->string('bairro', 44);            
        $table->string('celular', 14)->nullable();              
        $table->string('telefone', 13);              
        $table->string('cidade', 44);              
        /*$table->integer('city_id')->unsigned()->nullable();      
        $table->foreign('city_id')->references('id')->on('cities')
            ->onUpdate('cascade')
            ->onDelete('set null');  */      
        $table->string('estado', 2);                      
        $table->string('email', 44)->unique();                      
        $table->string('inscri_estadual', 44)->unique()->nullable();                      
        $table->string('inscri_municipal', 44)->unique()->nullable();                         
        $table->timestamps();
    });


}

Controller Pagamentos

public function index(){
    $pagamentos = Pagamento::all();
    $fornecedores = Fornecedor::all();

    return view('pagamentos.pagamento', 
       compact('pagamentos','fornecedores'));         
}

Model Pagamento

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Fornecedor;

class Pagamento extends Model
{
    //
    protected $table = 'pagamentos';

    protected $fillable = [
        'data_pag', 'valor', 'fornecedor_id','plano_contas',
    ];



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

Model Fornecedores

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Pagamento;


class Fornecedor extends Model
{
    //
    protected $table = 'fornecedores';

    protected $fillable = [
        'nome', 'cnpj', 'endereco', 'numero', 'cep', 'complemento', 'bairro', 'celular', 'telefone', 'cidade', 'estado', 'email', 'inscri_estadual', 'inscri_municipal',
    ];


    public function pagamento(){
        return $this->hasMany('App\Pagamento');
    }
}

{{ dd($pagamento) }}

inserir a descrição da imagem aqui

@foreach($pagamentos as $pagamento)
                            {{ dd($pagamentos) }}
                            <tr class="item{{$pagamentos->id}}">
                                <td>{{$pagamento->id}}</td>
                                <td>{{$pagamento->data_pag}}</td>
                                <td>{{$pagamento->valor}}</td>
                                <td>{{$pagamento->fornecedor_id->nome}}</td>
                                <td>{{$pagamento->plano_contas}}</td>
                                <td><button class="btnOpenUpdatePag btn btn-
info" data-id="{{$pagamento->id}}" data-data_pag="{{$pagamento->data_pag}}" 
data-valor="{{$pagamento->valor}}" data-pessoa="{{$pagamento->fornecedor_id-
>nome}}" data-plano_contas="{{$pagamento->plano_contas}}"> <span class="fa 
fa-pencil"></span></button>`
                                    <button class="delete-modal btn btn-danger" data-id="{{$pagamento->id}}" data-data_pag="{{$pagamento->data_pag}}" data-valor="{{$pagamento->valor}}" data-pessoa="{{$pagamento->fornecedor_id->nome}}" data-plano_contas="{{$pagamento->plano_contas}}" ><span class="fa fa-trash"></span></button>
                                </td>
                            </tr>
                            @endforeach

Payments with Vendor Id making the relationship right!

inserir a descrição da imagem aqui

PRINT SUPPLIERS TABLE

print tabela fornecedores

  • It’s actually quite simple.... in your model you have the relationship class Pagamento extends Model&#xA;{... public function fornecedores(){ then in your view, just access the function fornecedores() thus: <td>{{ $pagamento->fornecedores()->nome }}</td>

  • That mistake is because the field fornecedor_id is not an object, but an integer

  • Using this way I get the following error Undefined Property: Illuminate Database Eloquent Relations Belongsto::$name (View: C: xampp htdocs Esystemm Resources views payments payment.blade.php)"

  • To facilitate, in your view, do: <td>{{ dd($pagamento) }}</td> E put the result here

  • A print of the result on the question Edit

  • @Gabrielalves in your view use this way, $payment->suppliers()->get()->first()->name. if you only use supplier() refers to QB.

  • Trying to get Property 'name' of non-object (View: C: xampp htdocs Esystemm Resources views pagamentos pagamento.blade.php) Same error @arllondias , I believe everything is correct, the key Foreign is working I think the problem is in eloquent I followed the material of the Laravel about Hasmany and Belongsto and it is not working

  • In your database, all payments you are looking for have registered suppliers?

  • @arllondias Yes! And the Foreign key created by Migration is doing the right relationship. It’s the first time I do this with Laravel...

  • @arllondias Follow the print on Edit!

  • I’m going to try to simulate here, because the way I see it, that’s right

  • can take a print of suppliers table tbm?

  • @arllondias follows the print

  • Good here worked normally, I saw that in your code, has more than 1 place accessing supplier(). try switching all to supplier()->get()->first() and the attribute you need.

Show 9 more comments

1 answer

0


Well, as I mentioned in the comments, the way to access the attribute is incorrect. try this way (I put the table to show in print):

   <table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Data Pag</th>
            <th>Valor</th>
            <th>Fornecedor</th>
            <th>Plano Contas</th>
        </tr>
    </thead>
    @foreach($pagamentos as $pagamento)
        <tr data-data_pag="{{$pagamento->data_pag}}" data-valor="{{$pagamento->valor}}"
            data-pessoa="{{$pagamento->fornecedor()->get()->first()->nome}}"
            data-plano_contas="{{$pagamento->plano_contas}}">
            <td>{{$pagamento->id}}</td>
            <td>{{$pagamento->data_pag}}</td>
            <td>{{$pagamento->valor}}</td>
            <td>{{$pagamento->fornecedor()->get()->first()->nome}}</td>
            <td>{{$pagamento->plano_contas}}</td>
        <tr>
    @endforeach
</table>

inserir a descrição da imagem aqui

  • 1

    I found the error, I was using the name of the suppliers function in the model and using suppliers() in the view as well and for some reason was going wrong, I changed the function name in the model to supplier() and in the view to supplier() and now it is correct! I brought the data, thank you very much!

Browser other questions tagged

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