Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel-4 Polymorphic Relationship Only Assigning the Type (not the Id)

I am attempting to setup a polymorphic relationship with Laravel. I have read through the documentation and looked through related code but cannot seem to get all of it working. I am trying to attach photos to rooms where a room can have many photos. The type associated with the relationship works but the id is always 0.

Why would part of it work, and can someone please point out what any issues in my relationship?

I believe the problem is related to how I am creating the data in the table:

$photo = new Photo;
$photo->URL = 'thePhotoURL.extension';
$photo->save();

$room = new Room;
$room->name = 'Some Room Name';
// seems weird to me that I "save" the photo twice
// or am I just saving the relationship here?
// have tried the other relationship options too (associate, attach, synch)
$room->photos()->save($photo);
// have also tried:
// $room->photos()->save(new Photo(array('URL' => 'urlTest.com')));
// get error "URL"

$room->save();

Creating Photos table:

public function up() {
    Schema::create('photos', function($t) {

        $t->increments('id');

        // ... ...
        // the Id is always 0 but the type is correct
        $t->integer('imageable_id');
        $t->string('imageable_type');

        $t->softDeletes();
        $t->timestamps();

    });
}

And my classes,

Photo:

class Photo extends Eloquent {
    public function imageable() {
        return $this->morphTo();
    }
}

Room:

class Room extends Eloquent {       
    public function photos() {
        return $this->morphMany('Photo', 'imageable');
    }
}

I have seen an issue with reserved words (like Event) but that does not seem to be the issue here.

like image 421
Firo Avatar asked Dec 15 '25 12:12

Firo


2 Answers

You need to run $room->photos()->save($photo); after you save the original. The original doesn't exist yet, so there is no ID to associate.

Maybe it should throw an exception, maybe not. Personally, I would rather it scream at me.

like image 71
wesside Avatar answered Dec 18 '25 02:12

wesside


Use this:

$photo = $room->photos()->create(array('URL' => 'thePhotoURL.extension'));

like image 37
HiTech Avatar answered Dec 18 '25 02:12

HiTech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!