Skip to content
Advertisement

Using Eloquent to retrieve the parent category name?

i have a simple application for recursive hasMany relationship with unlimited subcategories the code is running without a problem but it’s not retrieving the parent category name or title.

when i tried to loop through the data coming from the DB it have the parent id but not the parent category name i need to get the parent category name here is the code for both controller and model

CategoryController.php

<?php

namespace AppHttpControllers;

use AppCategory;
use IlluminateHttpRequest;

class CategoryController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
         $parentCategories = Category::where('parent_id',1)->get();
         return view('welcome', compact('parentCategories'));
    }
}
?>

Category.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Category extends Model
{
    protected $guarded = [];

    public function subcategory(){

        return $this->hasMany('AppCategory', 'parent_id');

    }
}
?>

Advertisement

Answer

You should create another relation in same Category model.

public function parent() {
    return $this->belongsTo('AppCategory', 'parent_id');
}

And retrieving parent model will be like that:

$subcategory->parent->title;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement