Search code examples
phplaravellaravel-5laravel-5.3

Determine if the given foreign id is owned by the user?


What is good approach to determine if the given foreign id is owned by the user and return collection if found?

I have been doing like this, for example, in the controller:

public function showToken(Request $request)
{
  $this->tokenRepo->ownToken($request->user(), $request->toke);
}

In the tokenRepo class, the ownToken method look like this:

public function ownToken($user, $tokenId)
{
  return $user->tokens()->where('id', $tokenId)->first();
}

Solution

  • Returning explicit true or false value is a good practice. Also if you're checking token for currently logged in user, you could use auth()->user(). For example if repo is a model:

    public function ownToken($tokenId)
    {
        return is_null($this->where('id', $tokenId)
            ->where('user_id', auth()->user()->id)->first());
    }
    

    Or:

    public function ownToken($tokenId)
    {
        return is_null(auth()->user()->tokens()->where('id', $tokenId)->first());
    }
    

    Then you'll be able to do this:

    if ($this->tokenRepo->ownToken($request->token)) { .... }