M
M
maddog6702018-12-22 13:31:17
Laravel
maddog670, 2018-12-22 13:31:17

How to use method of one model in another Laravel model?

The essence of the question, is it possible to somehow get the getProjectDir () method in the User model without DI?
The relationship of the user to the project is one to one. There is a Project model and it has a getProjectDir() method

class Project extends Model
{
public function user()
    {
        return $this->belongsTo(User::class, 'id');
    }

public function getProjectDir()
    {
        return $this->project_dir;
    }
}

And the User model with the method
class User extends Model
{
public function project()
    {
        return $this->hasOne(Project::class, 'user_id');
    }

public function getAvatarAttribute($value)
    {	
        if(is_null($value)) {
            $avatar = '/img/admin/no-photo.jpg';
        }else{

            if(mb_strpos($value, "logo") !== false) {
                $avatar = '/storage/projects/images/'.$this->project->getProjectDir().'/'.$value;
            }else{
                $avatar = '/img/admin/'.$value;
            }
        }       

        return $avatar;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zhulan0v, 2018-12-22
@maddog670

$this->project->getProjectDir();
if this does not work for you, then look for a bug somewhere or there is simply no project in the database for this user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question