zefex
6 months ago

Help with laravel one to one relationship

Posted 6 months ago by zefex

I have a model that has an image cover and also many images as the other images of the gallery, that is how I tried to create the model:

class Ad extends Model
{
    protected $fillable = ['name', 'short_description', 'description'];

    public function cover()
    {
        return $this->hasOne(Image::class);
    }

    public function images()
    {
        return $this->hasMany(Image::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

The migration:

        Schema::create('ads', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('short_description');
            $table->text('description');
            $table->timestamps();
        });

The image model:

class Image extends Model
{
    protected $fillable = ['ad_id', 'image'];

    public function ad()
    {
        return $this->belongsTo(Ad::class);
    }
}

And the migration:

            $table->bigIncrements('id');
            $table->unsignedBigInteger('ad_id');
            $table->string('image');
            $table->timestamps();

            $table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade')->onUpdate('cascade');

The thing is that if I put an image on the database doesn't matter if I call cover() or images() from the Ad model it will always return the same image.

I was wondering, how to separate the cover image from the other images of the Ad keeping the Image model?

Please sign in or create an account to participate in this conversation.