Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Cataract0523's avatar

How to check if a record belongs to a user?

Let's say my User can make blog posts. I have now retrieved a blog post and I want check if the given blog post belongs to the authenticated user so it can be edited. I was able to accomplish that but it doesn't seem the best way to do it.

0 likes
4 replies
rawilk's avatar

What did you do?

I would set the user_id on the post and then do something like $post->user_id === auth()->id()

Cataract0523's avatar

@WILK_RANDALL - That is what I did. But I was wondering if there was something I could co using eloquent, like:

´´´ $post->user->has(Auth::user()) ´´´

rawilk's avatar

Sure, you can make whatever methods you want on your models. I would do it on the post though.

class Post extends Model
{
    public function ownedBy($userId = null)
    {
         $userId = $userId ?: auth()->id();

         return $this->user_id === $userId;
    }
}
1 like

Please or to participate in this conversation.