Laravel 5.4: I do not get data from Eloquent relationships

2

Using Laravel (with MySQL) I'm starting with Eloquent relationships. I try to get the related data but I do not get anything. My configuration is as follows:

Migration providers:

Schema::create('proveedores', function (Blueprint $table) {
            $table->increments('id');
            $table->string('razon_social')->unique();
            $table->string('ruc')->unique();
            $table->integer('id_rubro')->unsigned();
            $table->string('telf_contacto');
            $table->foreign('id_rubro')->references('id')->on('rubros')
                    ->onDelete('cascade')
                    ->onUpdate('cascade');
            $table->timestamps();
            $table->softDeletes();
        });

Migration items:

Schema::create('rubros', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nombre')->unique();
            $table->string('descripcion')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });

Provider model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Proveedor extends Model
{
    use SoftDeletes;
    protected $table = "proveedores";
    protected $hidden = ['created_at', 'updated_at', 'estado'];

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

Model Rubro:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Rubro extends Model
{
    use SoftDeletes;

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

ControllerController.php driver

$rubro = Proveedor::find(1);
dd($rubro);

Postman returns a series of results, but I can not see the blessed rubric . What should I do?

    
asked by Ricky 02.10.2017 в 03:28
source

1 answer

1

When you define the relationships in Eloquent, by default in belongsTo will try to use the name of the relationship as a foreign key and adding the string _id , which in this case is not fulfilled, so you must define the keys foreign as the second parameter in the relationship method:

public function rubro(){
    return $this->belongsTo('App\Rubro', 'id_rubro');
}

When you correct this small error, you should be able to access the relationship or the item with the dynamic properties.

Let's say that the most semantic way would be like this:

$proveedor = Proveedor::find(1);
$rubro = $proveedor->rubro;
dd($rubro);

The only "bad" thing about this method is that you are making two queries to the database to obtain the item. If you want to make only one query and have the preloaded item when you call the provider, you can use Eager Loading:

$proveedor = Proveedor::with('rubro')->find(1);
dd($proveedor->rubro);

More information in the Laravel documentation:

answered by 02.10.2017 / 03:42
source