I am using SQLite, and backpack, but I doubt that affects anything.
Anyway the issue is in the method public function category(): BelongsTo in the Content class
When I try to access the section, I get that it is null. I have even tried doing $section = Section::find($this->section_id); but I got null.
Even though it works fine outside the Content class, for example I can get the section, and it's not null, I can also get the category from the section, and it works fine,
Here are my models:
<?php
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Content extends Model
{
use CrudTrait;
use HasFactory;
protected $table = 'contents';
protected $primaryKey = 'id';
public $timestamps = true;
protected $guarded = ['id'];
protected $fillable = ['section_id', 'content', 'sub_content'];
// protected $hidden = [];
public function section(): BelongsTo
{
return $this->belongsTo(Section::class, 'section_id');
}
public function category(): BelongsTo
{
return $this->section->category();
}
}
<?php
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Section extends Model
{
use CrudTrait;
use HasFactory;
protected $table = 'sections';
protected $primaryKey = 'id';
public $timestamps = true;
protected $guarded = ['id'];
protected $fillable = ['title', 'category_id'];
// protected $hidden = [];
public function category(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Category::class, 'category_id');
}
public function contents(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Content::class, 'section_id');
}
}
<?php
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use CrudTrait;
use HasFactory;
protected $table = 'categories';
protected $primaryKey = 'id';
public $timestamps = true;
protected $guarded = ['id'];
protected $fillable = ['title', 'image_id'];
// protected $hidden = [];
public function sections(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Section::class, 'category_id');
}
public function image(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Image::class, 'image_id');
}
}