Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel (eloquent) accessors: Calculate only once

I have a Laravel model which have a calculated accessor:

Model Job has some JobApplications which are associated to a User. I want to get whether the user has already applied for a job or not.

For that I created an accessor user_applied which gets the applications relationships with the current user. This works okay, but the accessor is being calculated (making query) every time I access to the field.

Is there any easy way to calculate the accessor only once

/**
 * Whether the user applied for this job or not.
 *
 * @return bool
 */
public function getUserAppliedAttribute()
{
    if (!Auth::check()) {
        return false;
    }

    return $this->applications()->where('user_id', Auth::user()->id)->exists();
}

Thanks in advance.

like image 355
josec89 Avatar asked Mar 14 '23 05:03

josec89


2 Answers

I’d instead create a method on your User model that you pass a Job to, and returns a boolean as to whether the user’s applied or not:

class User extends Authenticatable
{
    public function jobApplications()
    {
        return $this->belongsToMany(JobApplication::class);
    }

    public function hasAppliedFor(Job $job)
    {
        return $this->jobApplications->contains('job_id', $job->getKey());
    }
}

Usage:

$applied = User::hasAppliedFor($job);
like image 44
Martin Bean Avatar answered Mar 27 '23 04:03

Martin Bean


As suggested in a comment and really not tricky at all

 protected $userApplied=false;
/**
 * Whether the user applied for this job or not.
 *
 * @return bool
 */
 public function getUserAppliedAttribute()
{
    if (!Auth::check()) {
        return false;
    }

    if($this->userApplied){
        return $this->userApplied;
    }else{
        $this->userApplied = $this->applications()->where('user_id', Auth::user()->id)->exists();

        return $this->userApplied;
    } 

}

like image 51
Mike Miller Avatar answered Mar 27 '23 04:03

Mike Miller