4
I’m trying to create a CRUD
simple category and subcategory registration where a category may have several subcategories but a subcategory may have only one category. On my migrátion I made my tables as follows:
Schema::create('sub_categorias', function (Blueprint $table) {
$table->increments('CdSubCategoria');
$table->integer('CdCategoria')->unsigned()->index();
$table->string('NmSubCategoria');
$table->string('DscSubCategoria');
$table->integer('FlgPontua');
$table->integer('QtdPontos');
$table->integer('MaxPontosPorSubCategoria');
$table->timestamps();
$table->softDeletes();
$table->foreign('CdCategoria')
->references('CdCategoria')
->on('categorias');
});
And my table of categories:
Schema::create('categorias', function (Blueprint $table) {
$table->increments('CdCategoria');
$table->string('NmCategoria', '50');
$table->string('DscCategoria', '255');
$table->timestamps();
$table->softDeletes();
});
Already in my category model I made:
use SoftDeletes;
protected $fillable = ['CdCategoria','NmSubCategoria', 'DscSubCategoria', 'FlgPontua', 'QtdPontos', 'MaxPontosCategoria'];
protected $primaryKey = 'CdSubCategoria';
protected $dates = ['deleted_at'];
public function categoria()
{
return $this->belongsTo('App\Categoria');
}
And in the subcategories:
use SoftDeletes;
protected $fillable = ['NmCategoria', 'DscCategoria'];
protected $primaryKey = 'CdCategoria';
protected $dates = ['deleted_at'];
public function subCategoria()
{
return $this->hasMany('App\SubCategoria');
}
With all this done my controller sends to a lisSubCategories view, where I want to list the subcategories and show the name of her parent category, in this way:
$subCategoria->categoria->NmCategoria
When performing this command together with dd()
is returned to me the error page describing the error:
Trying to get Property of non-object (View: ... views Subcategory listSubCategory.blade.php)
You are great ! Congratulations
– Renan Rodrigues