Okay, I'm not convinced that what I'm trying to do will even work. I've just created a blank Laravel project with the customary Post and Comment models.
Post Table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->unsignedInteger('duration');
$table->timestamps();
});
}
Comment Table
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained();
$table->text('body');
$table->timestamps();
});
}
Post Model
class Post extends Model
{
use HasFactory;
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Comment Model
class Comment extends Model
{
use HasFactory;
public function post()
{
return $this->belongsTo(Post::class);
}
public function scopeCalculate($query)
{
return $query->where('id', '=', $this->calculateDuration());
}
private function calculateDuration()
{
//return 1;
return $this->post->duration;
}
}
Database Seeder
class DatabaseSeeder extends Seeder
{
public function run()
{
$post = Post::create([
'title' => 'Post Title',
'body' => 'Body of the post. Some random text.',
'duration' => 1,
]);
$post->comments()->create([
'body' => 'A comment on the post.',
]);
}
}
Web Route
Route::get('/', function () {
return \App\Models\Comment::query()->calculate()->get();
});
I get the same error 'Attempt to read property "duration" on null'.