Courses

Laravel 12 Multi-Tenancy: All You Need To Know

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

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Basic filtering using where() clause in controllers
- Handling 403 errors for unauthorized access
- Implementing Global Scope in a model

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

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 21 video+text lessons of this course? (1 h 21 min)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord