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();
}
}
}