skip to Main Content

I have the following table in "Category" table.

id name parent_id
1 student NULL
2 teacher NULL
3 math_student 1
4 science_student 1

I have the following table in "Post" table.

id name category_id
1 Ajay 3
2 Mohan 3

Post.php file from Models

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

if I place the below code I am getting the name of 3rd id that is math_student.

$post->category->name

but I want to get the name of the parent_id of the category i.e. – "student"

I have tried the following code but it is wrong.

$post->category->parent_id->name

please suggest me the solution

2

Answers


  1. Within the Category Model, add parent relationship:

     public function parent(){
            return $this->belongsTo(Category::class, 'parent_id', 'id')->withDefault();
        }
    

    Then, you can get the parent name

    $post->category->parent->name
    
    Login or Signup to reply.
  2. You need to set up a relationship using parent_id to find the model instance of Category within itself.

    In the Category.php model:

    public function parent(){
        return $this->belongsTo(Category::class, 'parent_id', 'id');
    }
    

    After that, you will be able to:

    $post->category->parent->name;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search