Search code examples
phplaraveleloquentbelongs-tohas-one

LARAVEL - I want to access the main category from the category object with the upper _id column that contains the main category ID


I want to access the main category from the category object with the upper _id column that contains the main category ID.

Error: Cannot use object of type Illuminate\Database\Eloquent\Relations\BelongsTo as array

Categories migration :

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('upper_id')->default(0);
        $table->string('name', 100);
        $table->string('slug', 100);
        $table->string('description', 500)->nullable();
        $table->timestamps();
        $table->softDeletes();
    });

Category model :

class Category extends Model{
use SoftDeletes;
protected $fillable = ['upper_id', 'name', 'description', 'slug',];

public function companies()
{
    return $this->hasMany('App\Company', 'category_id', 'id');
}

public function up_category()
{
    $category = $this->belongsTo('App\Category', 'upper_id', 'id');
    return $category['name'];
}

CategoryController :

public function index()
{
    $categories = Category::where('deleted_at', null)->get();
    return view('admin.category.index', compact('categories'));
}

View :

@foreach($categories as $category)
                        <tr>
                            <td>{{ $category->name }}</td>
                            <td>{{ $category->up_category->name }}</td>
                        </tr>
@endforeach

Solution

  • change in your model function up_category

    public function up_category(){
        return $this->belongsTo('App\Category', 'upper_id', 'id')->withDefault([
        'name' => '-'
       ]);
    }
    

    Blade file correct.

     <td>{{ $category->up_category->name }}</td> //No change