Search code examples
phplaraveleloquentlaravel-api

function static::created does not save properly Laravel


So I have 2 tables: Item and Product. An Item hasMany Products and a Product belongsTo an Item.

Products migration:

Schema::create('products', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('hashed_id')->nullable()->unique();
    $table->bigInteger('item_id')->unsigned();
    $table->bigInteger('user_id')->unsigned();
    $table->integer('state')->default(1);
    $table->decimal('price');
    $table->string('slug')->nullable()->unique();
    $table->timestamps();

    $table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

For the hashed_id I use the following package: https://packagist.org/packages/hashids/hashids to create a hashed id to show in the url.

Product.php

public static function boot()
{
    parent::boot();

    static::created(function ($product) {
        $productId = $product->id;
        $hashids = new Hashids("", 10, 'abcdefghijklmnopqrstuvwxyz1234567890');
        $hashedId = $hashids->encode($productId++);

        $slug = Str::slug($product->item->slug . '-' . $hashedId);

        $product->hashed_id = $hashedId;
        $product->slug = $slug;
    });

}

ProductsController.php

public function createSelfProduct(Request $request)
{
    $product = auth()->user()->products()->create([
        'item_id' => $request->item_id,
        'user_id' => auth()->user()->id,
        'price' => $request->price,
    ]);

    // create the product and show seller info
    return new ProductResource($product->load('user'));
}

What I'm trying to do is that when a user creates a new product, it should get the slug from the item model, put the $hashedId behind it and save that to the db. Now, when I do a post request via Postman, I get the desired result, as hashed_id and slug are saved. But when I check the database, both hashed_id and slug are NULL. Only the item_id, user_id and price are saved. What am I doing wrong and how can I fix this?


Solution

  • The created event means the Model has already been created. This is not before save, but after it has been saved. If you alter anything at this point you will need to save the record again.

    Simply: You forgot to call save on your model instance to save the changes after you altered it.