Is this the start of a riddle? 🫤
Model Policy to prevent deleting ?
Hello,
A price has always a level, a funding, a type and a state.
A level, a funding, a type and a state have many sessions.
But a sessions has no price relationship because the amount is directly written in a float column (for convenience, if the amounts change one day or another, the amounts won't change in the past sessions).
So a price can't be deleted if it has at least one session which has the same level, funding, type and state than the price.
How can I write this in my policy ?
I tried something like that to begin and test.
// Delete policy
return $price->has('level.sessions')->count() == 0;
I'd better like something like this.
/**
* Determine whether the user can delete the model.
*
* @param \App\Models\User $user
* @param \App\Models\Price $price
* @return \Illuminate\Auth\Access\Response|bool
*/
public function delete(User $user, Price $price)
{
return $price->has('level.sessions', function ($query) use ($price) {
$query->where('level_id', $price->level_id);
});
}
But it doesn't work.
Then I have to add the same test for the funding, the type and the state.
Thanks for your help.
Vincent
or you can use
$query->withExists(['sessions' => fn($query) => $query
->whereCoulmn('prices.level_id', 'sessions.level_id')
->whereCoulmn('prices.funding_id', 'sessions.funding_id')
->whereCoulmn('prices.type_id', 'sessions.type_id')
->whereCoulmn('prices.state_id', 'sessions.state_id');
]);
and then in the delete policy
public function delete(User $user, Price $price)
{
return isset($price->sessions_exists) ? !$price->sessions_exists : Session::
where('level_id', $price->level_id)
->where('funding_id', $price->funding_id)
->where('type_id', $price->type_id)
->where('state_id', $price->state_id)
->count() == 0;
}
Please or to participate in this conversation.