DEV Community

Khandokar Nafis Jaman
Khandokar Nafis Jaman

Posted on

Restricted Access to Laravel Controller

In web apps, we need to restrict users from certain operations or functions often. Most Laravel developers use auth middleware in route.php or api.php files. We can also use the controller constructor to assign the middleware. It is more convenient as it restricts the middleware to only specific methods on a controller class. We can do this by following way:
`<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
//
public function __cinstruct()
{
# code...
return $this->middleware('auth');
}
public function index()
{
# code...
return view('home.index');
}
}
`

If you want to restrict a specific function, you can do this with only() method. Let's say, I need to apply my auth middleware for index method. Then the code will be:

`<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
//
public function __cinstruct()
{
# code...
return $this->middleware('auth')->only(['index']);
}
public function index()
{
# code...
return view('home.index');
}
}
`

We can also apply restrictions for all the methods except one. So if I want the middleware to be applicable for all functions except index, the code will be:

`<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
//
public function __cinstruct()
{
# code...
return $this->middleware('auth')->except(['index']);
}
public function index()
{
# code...
return view('home.index');
}
}
`

Happy Coding!!!

Top comments (0)