mercredi 27 février 2019

Unknown column 'imageable_type' in 'field list' when insert one-to-one polymorphic relation laravel 5

My Image migration

class CreateImagesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('images', function (Blueprint $table) {
        $table->increments('id');
        $table->string('url');
        $table->integer('imageable_id');
        $table->string(' imageable_type');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('images');
}
}

My Image model

class Image extends Model
{
/**
 * Get the store of the image
 */
public function store()
{
    return $this->morphTo('App\Store', 'imageable');
}

/**
 * Get the item of the image
 */
public function item()
{
    return $this->morphTo('App\Item', 'imageable');
}

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'url', 'imageable_id', 'imageable_type'
];
}

My Store model

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

/**
 * Get the items of a store
 */
public function items()
{
    return $this->hasMany('App\Item');
}

/**
 * Get the store's image.
 */
public function image()
{
    return $this->morphOne('App\Image', 'imageable');
}

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'address', 'description','user_id',
];
}

So I have Store,Item,Image models and a store/an item can own only one image.

And I am trying to save a store and an image belongs to that store in the 'store' action of the StoreController:

public function store(Request $request){
    $request->validate(....);

    $store = $user->stores()->create($request->all());

    // Upload the image to s3 and retrieve the url
    ...
    $url = Storage::disk('s3')->put($path, $image);
    Storage::cloud()->url($path);

    // Trying to save the image to databse
    $image = new Image(['url' => $url]);
    $store->image()->save($image); // => Error

}

I am following the example here but it does not work

Any pointers will be appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire