Setting a middleware for a controller, except a function in Laravel 5

Asked

Viewed 1,133 times

1

I’m starting to work now with Laravel and realized that setting the routes directly to the controls where I can set the type of HTTP request is more feasible for my application. Today I have something like this:

Routes.php

Route::controller("usuario","UsuarioController");

Usuariocontroller.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UsuarioController extends Controller 
{
    public function __construct() 
    {
        //$this->middleware("auth");
    }
    public function getAutenticar() 
    {
        return view("Usuario/Autenticar");
    }
}

My question is this. Is there any way I set a manual middleware within control where just for 2 routes I would be free from auth middleware?

I know if I set these routes manually in the file routes.php works but, doing this I can’t keep working using the request type setting HTTP within my controller.

I can somehow force my controller to accept 2 middleware, 1 for "x" methods and another for other methods?

  • What was the reason for the negative? Could inform.

1 answer

5


There are other ways to define a middleware in Laravel, but I’ll show you the way you need it, which is by setting it directly in Controller.

Option except

To define a middleware specific to a controller, just use the option except, for you to define which methods you do not want to apply the middleware specific:

Behold:

$this->middleware('meu_middleware', ['except' => 'logout']);

except means "except". It means that whatever is passed by parameter will be ignored by that middleware.

It is also possible to pass more than one value that will be ignored:

$this->middleware('meu_middleware', ['except' => ['logout', 'register']]);

Option only

If you just need to define where middleware will be applied (instead of applying the exceptions), you can use the option only - means "only".

Behold:

 $this->middleware('meu_middleware', ['only' => ['listar', 'deletar']]);
  • excellent! this worked exactly as I needed... I was even thinking about creating another unnecessary class to separate the functions being that it is all 1 method

Browser other questions tagged

You are not signed in. Login or sign up in order to post.