Kloumpitz
8 months ago

Best practice for checking relationship between models?

Posted 8 months ago by Kloumpitz

Hi, lets say I have a User and a Post-Model with an hasMany-Relationship between them.

My PostController:

class PostController extends Controller
{
    ...
    public function show($id)
    {
        // ... Get the Post from Database by $id
    }
}

My question is: What is the best, most elegant way to get the post from the DB while checking, if it belongs to the currently authenticated User?

I did something like this - and it works. But it doesn't seem very clean...

$p = Auth::user()->posts()->where('id', $post->id)->first();

Or should i go with Middleware? How would i do that?

I am happy to hear your suggestions - thanks alot!

Please sign in or create an account to participate in this conversation.