Checking if the user has permission for something is called gates or policies https://laravel.com/docs/8.x/authorization#creating-policies
Laravel API: Best way to check if requested data exists
Hi,
I am writing some API endpoints to check activity for a specific user in a specific forum thread. I have 4 different endpoints that start with the same actions:
- Check if the forum thread belongs to the authenticated user (this is the actual owner of the thread, not the user we are requesting the activity from).
- Check if the requested user (the user for which we request the activity, not the authenticated user) is subscribed to the thread.
$thread = Thread::where('id', $id)
->where('customer_id', auth()->user()->id)
->first();
if (!$thread) return response()->json(['message' => 'Thread not found'], 422);
$user = UserLinked::where('thread_id', $id)
->where('user_id', $userId)
->first();
if (!$user) return response()->json(['message' => 'User not found'], 422);
I was thinking to create a FormRequest and check in the rules function (see below). But the parameters I am using are route parameters and not post parameters which causes the validation to give errors as 'id' and 'userId' are not found in post parameters.
public function rules()
{
$id = $this->route('id');
$userId = $this->route('userId');
$customerId = auth()->user()->id;
return [
'id' => [
'required',
Rule::exists('thread')->where(function ($query) use ($id, $customerId) {
$query->where('id', $id)->where('customer_id', $customerId);
}),
],
'userId' => [
'required',
Rule::exists('user_linked')->where(function ($query) use ($id, $userId) {
$query->where('thread_id', $id)->where('user_id', $userId);
}),
],
];
}
I am a bit lost on how to handle this the best way to avoid code replication. Do I just write a function in my controller that checks for the validity? This will result in something like this which I don't like either..
if (!($thread = $this->threadFound($id)))
return response()->json(['message' => 'Thread not found'], 422);
if (!($linked = $this->userFound($id, $userId)))
return response()->json(['message' => 'User not found'], 422);
Any other suggestions on how to handle this the best and cleanest way?
Please or to participate in this conversation.