I have setup simple belongsTo HasMany between my Listing.php model and my User Model.
User.php
namespace App\Models;
use App\Models\Curated\Listing;
public function listings()
{
return $this->hasMany(Listing::class);
}
Listing.php
namespace App\Models\Curated;
use App\Models\User;
/**
* Get the user that owns the Listing.
*/
public function owner()
{
return $this->belongsTo(User::class);
}
And in my listing migration
Schema::create('listings', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique();
$table->string('name')->nullable();
$table->mediumText('blurb')->nullable();
$table->foreignId('community_id');
$table->foreignId('user_id');
$table->string('largeImagePath')->nullable();
$table->string('thumbImagePath')->nullable();
$table->char('status', 1)->default('d');
$table->integer('order')->unsigned()->default(0);
$table->timestamps();
});
If I create a listing and then do
return auth()->user()->listings()->get();
I get
"id": 1,
"slug": "badnda-1",
"name": "Badnda",
"blurb": "<h3>xzsxzsx</h3><p></p><p>xzsxzsxzsxzsx</p><p>xzsxzsx</p>",
"community_id": 1,
"user_id": 1,
"largeImagePath": "listing-images/badnda-1-1/badnda-1.webp",
"thumbImagePath": "listing-images/badnda-1-1/badnda-1-thumb.webp",
"status": "p",
"order": 0,
"created_at": "2021-07-02T23:16:58.000000Z",
"updated_at": "2021-07-02T23:16:58.000000Z"
However if I do
return Listing::find(1)->owner()->get();
I get an empty array. How do I start troubleshooting this? I tried doing
return $this->belongsTo('App\Models\User');
but that still returns empty.