you need get $thread
$t = Threads::findorfail($thread);
return view .........
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
So yesterday i create a new project and declared some relationship. Here are my migration
/**
*
* Thread migration
*
* @return void
*/
public function up()
{
Schema::create('threads', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->unsignedBigInteger('user_id')->index();
$table->text('body')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')
->on('users')->cascadeOnDelete();
});
}
and the Reply migration
/**
* Reply migration.
*
* @return void
*/
public function up()
{
Schema::create('replies', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('thread_id');
$table->text('body')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')
->on('users')->cascadeOnDelete();
$table->foreign('thread_id')->references('id')
->on('threads')->cascadeOnDelete();
});
}
Also here are the models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model
{
use HasFactory;
protected $fillable = [ 'user_id', 'title', 'body' ];
public function user(){
return $this->belongsTo(User::class);
}
/**
* Fetch a path to the current thread.
*
* @return string
*/
public function path()
{
return '/threads/' . $this->id;
}
public function replies(){
return $this->hasMany(Reply::class);
}
}
Reply model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Reply extends Model
{
use HasFactory;
protected $fillable = ['user_id', 'body', 'thread_id'];
public function owner(){
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function thread(){
return $this->belongsTo(Thread::class, 'thread_id', 'id');
}
}
the challenge is that i cannot get the replies even when i have records in my databse. this is my controller method.
/**
* Display the specified resource.
*
* @param \App\Models\Thread $thread
* @return \Illuminate\Http\Response
*/
public function show(Thread $thread)
{
$thread->load('replies');
return view('threads.show', compact('thread'));
}
However, when i use tinker session it works. I am using laravel 9.45. i cannot seem to understand what's going on. I am completely stucked.
Everything looks correct. I assume you don't get any errors.
Can you try using debugbar to see what queries are being run?
Please or to participate in this conversation.