Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tomasosho's avatar

I want to get the category name in sub_category edit

My controller

$subcategory = SubCategory::find($id);
        $cat = ProductCategory::find($subcategory->category_id);
        dd($cat);

I am getting the value for ````subcategory, but my $catis giving menull```;

0 likes
3 replies
rodrigo.pedra's avatar

1 - can you show the result of dd($subcategory)?

2 - Does the SubCategory model have a relation method defined with ProductCategory?

3 - Can you show the migration for the ProductCategory model?

tomasosho's avatar

dd($subcategory)

App\SubCategory {#1488 ▼
  #primaryKey: "id"
  #connection: "mysql"
  #table: "sub_categories"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:8 [▶]
  #original: array:8 [▼
    "id" => 1
    "category_id" => "1"
    "name" => "Nokias"
    "slug" => null
    "description" => "Nokia Phones"
    "status" => 1
    "created_at" => "2020-10-28 19:32:45"
    "updated_at" => "2020-10-28 22:08:08"
  ]

Yes Productcategory Model

public function subcategories(){

        return $this->hasMany(SubCategory::class, 'category_id', 'id');

    }

Migration

Schema::create('product_categories', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('slug')->unique('slug')->nullable();
            $table->text('description')->nullable();
            $table->tinyInteger('status')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });

Migration for sub categories

Schema::create('sub_categories', function (Blueprint $table) {
            $table->id();
            $table->string('category_id')->nullable();
            $table->string('name')->nullable();
            $table->string('slug')->unique('slug')->nullable();
            $table->text('description')->nullable();
            $table->tinyInteger('status')->default(0);
            $table->timestamps();
        });
rodrigo.pedra's avatar
Level 56

Add, if not exists, to the SubCategory model:

public function productCategory(){
    return $this->belongsTo(ProductCategory::class, 'category_id', 'id');
}

And then try running this:

$subcategory = SubCategory::with(['productCategory'])->find($id);
$cat = $subcategory->productCategory;
dd($subcategory, $cat);
1 like

Please or to participate in this conversation.