skip to Main Content

This is the first time I’m facing this issue, when adding an if statement in a model attribute and trying to load the page i get an error that the site can’t be reached, although when removing the if statement the page loads perfectly, what could be the problem?

The problem occurs in the getGeneratedNameAttribute

Code Example:

<?php

namespace AppModels;

use CarbonCarbon;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class orderPayment extends Model
{
    use HasFactory;

    protected $appends = ['generatedName'];


    protected $guarded = [];

    public function order() {
        return $this->belongsTo(Order::class, 'order_id');
    }

    public function notes() {
        return $this->hasMany(Note::class, 'payment_id');
    }

    public function partPayments() {
        return $this->hasMany(PartPayment::class, 'payment_id');
    }

    public function getGeneratedNameAttribute() {

      
        if($this->order->retainer) {
            $monthName = Carbon::now()->day(1)->month($this->month)->translatedFormat('F');
            
            return 'Month '.$monthName.' '.$this->year;
        }
      
        return $this->name;
        

    }

}

Laravel Version: v10.12.0

2

Answers


    1. Check if the $this->order relationship is defined correctly and if
      it returns the expected result. Make sure that the order_id foreign
      key in the order_payment table corresponds to the primary key of the
      Order model.

    2. Verify that the retainer attribute exists in the Order model. If it
      doesn’t exist or has a different name, it could cause an error when
      accessing $this->order->retainer.

    3. Ensure that the order relationship is eager loaded when retrieving
      the orderPayment model. If it’s not eager loaded, accessing
      $this->order could trigger additional queries, which may cause
      performance issues or errors.

      $orderPayment = OrderPayment::with('order')->find($id);

      Please ensure the above steps.

    Login or Signup to reply.
  1. try this if it works for you.

    public function getGeneratedNameAttribute()
    {
        if ($this->order && $this->order->retainer) {
            $month = Carbon::now()->month($this->month);
            $monthName = $month->translatedFormat('F');
    
            return 'Month ' . $monthName . ' ' . $this->year;
        }
    
        return $this->name;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search