Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Filter Model By user_id: With where() and Global Scope

Premium
3:10

So now that we have the user_id in our DB table, let's filter by that, so that each user would access only their projects.


Option 1. Straightforward where()

Of course, the most typical filter method is to filter with the where() statement.

app/Http/Controllers/ProjectController.php:

class ProjectController extends Controller
{
public function index()
{
$projects = Project::where('user_id', auth()->id())->get();
 
return view('projects.index', compact('projects'));
}
 
// ...
}

If I register with a new user and visit the Projects page, I will not see any projects.

But the problem is I can still enter the Edit page for other projects by guessing the URL of /projects/1/edit even if different user has created that project.

So, you must add those where() conditions in...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

P
pharmonie ✓ Link copied!

This is really cool and I like the approach with the global scope very much. But what if an Admin signs in, that is able to see a list of all projects?

PK
Povilas Korop ✓ Link copied!

You can add an if statement at the scope, that if the user is admin then not apply the global scope.

DS
D.H SIMON ✓ Link copied!

Hi, the video links seems faulty :

This site can’t be reached The webpage at https://player.vimeo.com/video/709093819?h=313c197da8&badge=0&loop=false&byline=false&portrait=false&title=false&speed=true&transparent=0&gesture=media might be temporarily down or it may have moved permanently to a new web address.

M
Modestas ✓ Link copied!

Hi, this could be due to country limitations done by Vimeo. Please check if vimeo.com works in your country (there is nothing we can do to change which countries they support, sorry)

OK
Oliver Kurmis ✓ Link copied!

The problem with the global scope is that in jobs or command there is not authenticated user, auth() will return null.

Why not just use auth()->user()->projects in the controller ?

M
M ✓ Link copied!

Seeder also sees an issue with this approach. Authenticating as the user first becomes slow: Auth::login($user);

AI
Ariful Islam ✓ Link copied!

awesome content