Rukmi Patel Rukmi Patel - 5 months ago 26
PHP Question

Laravel - Don't allow user to access other user data

In Laravel, How can we restrict user to access other user's data?

Do I need to write down code in each and every route functions? or does laravel provides centric approach?


Though I don't know your use-case, let suppose you want to protect your user from seeing other user's profile. Now if your show user route is something like


Then just create a middleware let's say myAuth

class MyAuth
  public function handle($request, Closure $next)
    if(!auth()->check && !auth()->user()->id == request()->get('id'))
      dd("you are not allowed to see this");

    return $next($request);

and include it in your Http/kernel.php

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'admin' => \App\Http\Middleware\Admin::class,
    //Your new middleware
    'myAuth' => \App\Http\Middleware\MyAuth::class,

And include your routes in this middleware

Route::group(['middleware' => 'myAuth'], function () {    
    Route::get('user/{id}', function () {
        //Only user with id 1 can see profile of user with id 1