I have a users migration as follows:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
And a BlogPosts migration as follows:
Schema::create('blog_posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('title')->unique();
$table->string('image');
$table->text('text');
$table->timestamps();
});
They each have a Model (BlogPost and User)
On BlogPost Model i have the following:
public function getUser(){
return $this->belongsTo(User::class);
}
I have added some testdata to the DB as follows:
user table:
ID: 1, email: test@test.com, password: hashed
blog_post table:
ID: 1, title: title, image: /image.jpg, text: some text, user_id: 1
Now in tinker I do the following:
$var = \App\Models\BlogPost::find(1);
$var->getUser(); //Outputs: null
If I modify getUser to:
public function getUser(){
return $this->belongsTo(User::class)->toSql();
}
The output from tinker is:
select * from
userswhereusers.idis null
What am I doing wrong here?, am I missing something?