'Relationship returning nothing when trying to reference
I am currently trying to reference all the guilds the user belongs to, but right now, it doesn't seem to be working as intended. When I try to use $user->guilds(), it shows that it has a relation but doesn't return anything. So I thought I might need to do a pivot table.
User Migration
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id')->unsigned();
$table->string('descrim');
$table->bigInteger('snowflake')->unsigned();
$table->string('name')->nullable();
$table->string('username');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('avatar')->nullable();
$table->string('banner')->nullable();
$table->boolean('mfa_enabled')->default(false);
$table->boolean('verified')->default(false);
$table->rememberToken();
$table->timestamps();
});
Guild Migration
Schema::create('guilds', function (Blueprint $table) {
$table->bigInteger('id');
$table->bigInteger('user_id')->unsigned();
$table->bigInteger('user_snowflake')->unsigned();
$table->string('name');
$table->string('icon');
$table->string('owner_id')->nullable();
$table->string('permissions');
$table->string('permissions_new');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
User Model
namespace App\Models;
use App\Models\Guild;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $guarded = [];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function guilds()
{
return $this->hasMany(Guild::class);
}
}
Guild Model
namespace App\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Guild extends Model
{
use HasFactory;
protected $guarded = [];
public $incrementing = false;
public function user()
{
return $this->belongsTo(User::class);
}
}
Solution 1:[1]
Remove (), instead of $user->guilds() do $user->guilds.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Guille |

