Wimal Weerawansa
Wimal Weerawansa

Reputation: 157

Laravel Eloquent saving relational model fails

I have Laravel Eloquent class Collage

class Collage extends Model
{

    /**
     * Get the User that owns this Collage.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Collage migration schema

Schema::create('collages', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('name')->nullable();
            $table->timestamps();
        });

and User

class User extends Authenticatable
{
    /**
     * Get all Collages that belongs to this User.
     */
    public function collages()
    {
      return $this->hasMany('App\Collage');
    }
}

but when I do this on tinker

$user = App\User::find(1)->first();
$collage = new App\Collage;
$collage->name = 'Collage';
$collage->user = $user;

//and save
$collage->save();

throws me error QueryException

General error: 1 table collages has no column named user

Upvotes: 1

Views: 97

Answers (2)

KmasterYC
KmasterYC

Reputation: 2354

Change

$collage->user = $user

To

$collage->user_id = $user->id

Upvotes: 1

Pete Houston
Pete Houston

Reputation: 15079

Update your schema to make the relationship,

Schema::create('collages', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->string('name')->nullable();
    $table->timestamps();
});

That way Laravel Eloquent will automatically make references to the relationship.

Upvotes: 1

Related Questions