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

agruenberg's avatar

Preventening URL misuse with id change

Hi

I have 3 tables:

  • Users
  • Articles
  • Posts

Furthermore I'm using Route::resource('article.post, 'PostController');, so Laravel creates an URL like http://myGreatArticles.doom/article/4/post to list all posts for th article with ID 4. If I change the article ID within the url (for example to http://myGreatArticles.doom/article/404/post), Laravel will list all posts for article with ID 404, even this article does not belong to the current user. I s there any fancy Laravel mechanism to prevent this misbehaviour, or do I have to implement something like if ($article->user_id != Auth::user()->id) {...} in each single method within the Controller?

Thank you in advance

0 likes
7 replies
Swaz's avatar
Swaz
Best Answer
Level 20

There's a bunch of different ways to go about doing this: keep the logic in your controller, use a middleware, create a policy, etc. I would personally avoid writing if ($article->user_id != Auth::user()->id) every time because you can make it more readable using policies.

Have a look at the authorization docs. Link

Theres a good video on policies here. Link

And they're also used in the intermediate tutorial. Link

1 like
vikin's avatar

You may need to Middleware ,using Middleware to filter to the user

agruenberg's avatar

@Swaz Ok, I implemented a policy. The code is now: if(policy($article)->listPosts(Auth::user(),$article)). This works great (and also solves my problem ;), but where is the benefit (except better readable)? I have to implement this still to every method within the controller.

@francocorrea Security through obfuscation is always a very bad idea.

@vikin How would your solution look like?

Thank you everybody for the ideas!!!

agruenberg's avatar

@Swaz please forget my question above. I understand the concept now, I can put more than one rule within the method in the policy... Sorry ;)

Swaz's avatar

@agruenberg Yea, policies are very useful. Have a look at the video I posted, Jeffrey explains it all really well.

Please or to participate in this conversation.