Hello i have parent table and child table sessions. Which i use to create student schedule.
terms
-----
id
name
start_date
end_date
term_type
active
sessions
--------
id
term_id
start_date
end_date
session_type
Here's the relationship
public function term()
{
return $this->belongsTo('App\Models\Term', 'term_id');
}
public function sessions()
{
return $this->hasMany('App\Models\Session', 'term_id', 'id');
}
In my Session Model i have this attribute to delete a session record.
When future session is present terms page. Inner session page should not be allowed to be deleted.
Example:
Current session is august-september
future session should be october-december.
This logic seems to be tricky for me, i have tried to compare both end_date
and start_date
i realize its not going to work because it just compare itself. Honestly im not sure what im doing anymore.
public function getAllowDeleteAttribute()
{
if($this->term()->where('end_date') > $this->term()->where('start_date')){
return !($this->schedules()->exists() || $this->sessionFees()->exists());
}
}
The result is current session cannot be deleted. All i want is to restrict any user to delete future sessions not the current.
CodePudding user response:
If I understood your question correctly it should be somenthing like this:
public function getAllowDeleteAttribute()
{
if($this->term()->whereDate('start_date', '<=', today())->count()){
return !($this->schedules()->exists() || $this->sessionFees()->exists());
}
}
Also don't forget to pre-load your relationship in controller for better performance:
$sessions = Session::with('terms')->get();