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.
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);
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With