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

bobby_by's avatar

Deny access by URI to the items in the database if it's don't belonged to the current user.

I have a database table where we store all products for all user. We getting product page by product id number something like this http://sitename.com/inventory/product/3 .

How can I deny access to the product by url if this product doesn't belongs to the current user?

0 likes
2 replies
jlrdw's avatar

There's actually some free videos on this in this series, authentication and authorization: https://laracasts.com/series/laravel-from-scratch-2018

But that's what the auth id is for.

Use that series along with the newer 6.* scaffolding.

https://laravel.com/docs/6.x/authentication#retrieving-the-authenticated-user

Note also, there's a entire chapter on both in the docs.

Also authorization is a fairly large learning curve, hard to give a month lesson in a forum post.

You may want to look at https://github.com/spatie/laravel-permission this may be easier to get up and running. Note, still a big learning curve however.

ARG's avatar

Look into either:

Option 1: Using Middleware

Option 2: Redirect in the Controller

The controller you've got set up presumably has an $id value that is passed to the route or that is otherwise accessible. Add a statement like:

// Toward the start of the controller. 
// This Eloquent query syntax might be off. Replace with your query.
$product = \Auth::user()->with('products')->find($id);
if ( !$product ) { 
    // Redirect the user back to the previous page.
    // The withErrors value can be used/displayed as described in 
    // the Stack Overflow thread linked below
    return redirect()->back()->withErrors(['You must purchase this product to access this webpage.']);

    // Or alternatively
    die("Error: You do not have access to this product. Click <a href='#'>here</a> to buy it/return to home/other."); 
} 

// Put the rest of the controller below this 

See also:

Please or to participate in this conversation.