0
votes

I have defined parent relation within category class using 'parent_id' as mentioned below, I want to print category title with parent title like mens > show. but it throws

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$title

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
    protected $table = 'categories';


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

    public function withParentTitle(): string
    {               
        if($this->parent()){            
            return $this->parent()->title.' > '. $this->title;
        }
        return $this->title;
    }   


}

CategoryController

................

namespace App\Http\Controllers;

use App\Category;

class CategoryController extends Controller
{

    public function index(){        
        $categories = Category::get();
        foreach($categories as $category){
            echo $category->withParentTitle();
        }
    }
}
3

3 Answers

1
votes

according to laravel docs https://laravel.com/docs/5.8/eloquent-mutators

you can use accessors by this way

public function getParentTitleAttribute(){
  return $this->parent ? $this->parent->title . '>' . $this->title : $this->title;
}

then call $category->parent_title;

0
votes

You have to do the call without () like this :

public function withParentTitle(): string
{               
    if($this->parent()){            
        return $this->parent->title.' > '. $this->title;
    }
    return $this->title;
}

Because if you use the () you are callin the relation as query builder and you can use other closures :

$this->parent()->where('title', 'foo')->first();
0
votes
public function withParentTitle(): string
    {               
        // Your $this->parent() would always be true, 
        // use $this->parent()->exists() instead
        if($this->parent()->exists()){            
            // $this->parent() refers to the relationship, 
            // you can't get title out of the relationship object, 
            // unless you retrieve it using $this->parent
            return $this->parent->title.' > '. $this->title;
        }
        return $this->title;
    }