trzew
trzew

Reputation: 455

Adding a new field in the model in Laravel

I am beginner in Laravel.

I need to add an extra field with artist name as a result of my model. I'll need it for JSON and ARRAY

I have this code:

public function up()
    {
        Schema::create('feature_product', function (Blueprint $table) {
            $table->id();
            $table->foreignId('product_id')->constrained('products')->onDelete('cascade');
            $table->foreignId('feature_id')->constrained('features')->onDelete('cascade');
            $table->foreignId('feature_value_id')->nullable()->constrained('feature_values')->onDelete('set null');
            $table->string('custom_value')->nullable();
            $table->timestamps();
        });
    }


Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('product_category_id')->nullable()->constrained('product_categories')->onDelete('set null');
            $table->foreignId('image_id')->nullable()->constrained('images')->onDelete('set null');
            $table->foreignId('vat_type_id')->nullable()->constrained('vat_types')->onDelete('set null');

            $table->string('name');
            $table->string('slug');
            $table->text('lead')->nullable();
            $table->text('description');
            $table->decimal('price', 10, 2);

            $table->deactivation();
            $table->timestamps();
            $table->softDeletes();
        });

Models:

 class Product extends Model implements Presentable
{
    use SoftDeletes,
        Deactivation,
        Seoable,
        Taggable,
        Translatable,
        Imageable;

    protected $appends = array(
        'artist' => ''
    );

    protected $fillable = [
        'name',
        'slug',
        'lead',
        'description',
        'price',
        'product_category_id',
        'image_id',
        'vat_type_id'
    ];

    protected $dates = [
        'deactivated_at',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $casts = [
        'image_id' => 'integer',
        'product_category_id' => 'integer',
        'vat_type_id' => 'integer',
        'min_student_level' => 'integer',
        'price' => 'decimal:2'
    ];

    protected $hidden = [
        'product_category_id',
        'image_id',
        'vat_type_id',
        'deactivated_at',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    public function image(): BelongsTo
    {
        return $this->belongsTo(Image::class);
    }

    public function productCategory(): BelongsTo
    {
        return $this->belongsTo(ProductCategory::class);
    }

    public function vatType(): BelongsTo
    {
        return $this->belongsTo(VatType::class);
    }

    public function features(): BelongsToMany
    {
        return $this->belongsToMany(Feature::class)->withPivot('feature_value_id', 'custom_value');
    }

    public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
    {
        return new ProductUrlPresenter($this);
    }

    public function getPriceFormattedAttribute(): string
    {
        return Str::price($this->price);
    }

    public function getPriceNettoAttribute(): string
    {
        $priceNetto = (1 - $this->vatType->value / 100) * $this->price;
        return Str::price(max(0, $priceNetto));
    }

    public function getArtistAttribute()
    {
        $features = $this->features()->get();
        if (count($features) > 0 ) {
            foreach ($features as $feature) {
                if (isset($feature->pivot) && $feature->name == "Artysta") {
                    return $this->appends['artist'] =  $feature->pivot->custom_value;
                }
            }
        }
    }

    public function artist()
    {
        return $this->getArtistAttribute();
    }

When I debug my model I have this result:

$products = $this->productRepository->getMany(['artist'])->sortBy('name');
        dd ($products);

I have result:

{
    "message": "Call to a member function addEagerConstraints() on string",
    "exception": "Error",
    "file": "/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php",
    "line": 586,
    "trace": [
        {
            "file": "/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php",
            "line": 564,
            "function": "eagerLoadRelation",
            "class": "Illuminate\\Database\\Eloquent\\Builder",
            "type": "->"
        },
        {
            "file": "/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php",
            "line": 532,
            "function": "eagerLoadRelations",
            "class": "Illuminate\\Database\\Eloquent\\Builder",
            "type": "->"
        },
        {
            "file": "/var/www/app/Repositories/Base/BaseRepository.php",
            "line": 84,
            "function": "get",
            "class": "Illuminate\\Database\\Eloquent\\Builder",
            "type": "->"
        },
        {
            "file": "/var/www/app/Http/Controllers/Json/ProductListController.php",
            "line": 22,
            "function": "getMany",
            "class": "App\\Repositories\\Base\\BaseRepository",
            "type": "->"
        },
        {
            "function": "list",
            "class": "App\\Http\\Controllers\\Json\\ProductListController",
            "type": "->"
        },

When I run my code without "artists":

$products = $this->productRepository->getMany(['image', 'productCategory', 'features'])->sortBy('name');
        dd ($products);

I havent error, but append artist is empty:

Illuminate\Database\Eloquent\Collection {#1422 ▼
  #items: array:2 [▼
    1 => App\Models\Catalog\Product {#1447 ▼
      #appends: array:1 [▼
        "artist" => ""
      ]
      #fillable: array:8 [▶]
      #dates: array:4 [▶]
      #casts: array:6 [▶]
      #hidden: array:7 [▶]
      #connection: "mysql"
      #table: "products"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:13 [▼
        "id" => 2
        "product_category_id" => 3
        "image_id" => 1
        "vat_type_id" => 1
        "name" => "Album 2"
        "slug" => "album-2"
        "lead" => "<p>fwe</p>"
        "description" => "<p>fwe</p>"
        "price" => "54.00"
        "deactivated_at" => null
        "created_at" => "2020-10-05 11:49:22"
        "updated_at" => "2020-10-05 11:49:22"
        "deleted_at" => null
      ]
      #original: array:13 [▶]
      #changes: []
      #classCastCache: []
      #dateFormat: null
      #dispatchesEvents: []
      #observables: []
      #relations: array:3 [▶]
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }

How can I repair it?

What's is wrong?

Please help me

Upvotes: 1

Views: 2350

Answers (1)

Kamlesh Paul
Kamlesh Paul

Reputation: 12401

you need to add new $appends property like this

protected $appends = ['artist']

public function getArtistAttribute()
    {
        $features = $this->features()->get();
        if (count($features) > 0 ) {
            foreach ($features as $feature) {
                if (isset($feature->pivot) && $feature->name == "Artysta") {
                    return $feature->pivot->custom_value;
                }
            }
        }
    }

then getArtistAttribute return that value you want to assgin

Upvotes: 4

Related Questions