Home > Software engineering >  PhpStorm 2022.2.2 Laravel Model Relationships and Attributes recognised as magic methods
PhpStorm 2022.2.2 Laravel Model Relationships and Attributes recognised as magic methods

Time:09-17

How can I declare my model relationships and custom attributes properly so that they will be available from auto-completion and have the warning "property accessed via magic method" disappear?

I have nothing above my Model class and I've tried a few examples but none seems to work. i.e @method, @param or I just can't figure out the proper syntax for it.

quantity_remaining is a custom attribute for my Model.

I have it like this ATM:

class MyModel extends Model
{

    /**
     * @return HasOne
     */
     public function packages(): HasOne{
          return $this->hasOne(Package::class, 'related_id', 'related_id');
     }

     public function getQuantityRemainingAttribute(): Int{
            //more codes here but not needed for this example
    
            return 1;
        }
}

enter image description here

enter image description here

CodePudding user response:

You might want to define properties in the class doc block. I renamed the packages relationship to package, because it is a hasOne relationship.


/**
* @property Package $packages
* @property int quantity_remaining
*/

class MyModel extends Model
{
     public function package(): HasOne{
        return $this->hasOne(Package::class, 'related_id', 'related_id');
     }

     public function getQuantityRemainingAttribute(): Int{
        return 1;
    }
}

CodePudding user response:

You will need to define fields in model class like:

public mixed $name;
public mixed $surname;
public mixed $email;
public mixed $password;

while your fillables are:

protected $fillables = ['name', 'surname', 'email', 'password'];
  • Related