'Please help improve the data to be compiled [closed]
I have data with the table as follows: enter image description here
In my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'parent_id', 'name', 'url', 'description', 'sort_order',
];
public function parent()
{
return $this->belongsTo('App\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function getParentsAttribute()
{
$parents = collect([]);
$parent = $this->parent;
while (!is_null($parent)) {
$parents->push($parent);
$parent = $parent->parent;
}
return $parents->implode('name', ' > ');
}
}
In my Controller:
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CategoryController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function listCategory()
{
$categories = Category::orderBy('sort_order')->get();
// dd($categories);
return view('catalog.category.list', ['categories' => $categories]);
}
}
But I can not match expectations.
Solution 1:[1]
I change $parents->push($parent);
to $parents->prepend($parent);
in my Model and this problem solved.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Septian Dwic. |