jeudi 27 juin 2019

How to make a one to one eloquent relation in Laravel?

I created my migration by using the artisan command

php artisan make:model Player -m

My migration then looked like this:

public function up()
{
    Schema::create('players', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id')->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete$
        $table->string('username');
        $table->timestamps();
    });
}

Which left me no errors when I ran

php artisan migrate

I then updated my Player model App/Player.php to include the fillables and one to one relation

class Player extends Model
{
    protected $fillable = ['user_id', 'username'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

I then ran the Tinker artisan and my output when I try to access the player model is this

>>> User::find(1)->player;
=> null

What am I missing?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2IRTl8X
via IFTTT

Aucun commentaire:

Enregistrer un commentaire