Laravel 5.6 Apply Middleware for controller certain methods


Laravel 5.6 Apply Middleware for controller certain methods



Laravel 5.6 Apply Middleware for controller certain methods



https://laravel.com/docs/5.6/controllers#controller-middleware



without write a new class


class UserController extends Controller
{
public function __construct()
{
// how can apply this middleware for certain methods eg. store, update ?
$this->middleware(function ($request, $next) {
// i need modify the $request->input('name')
// before goes to method store, update

// replace any space+ to a single space
$request->merge(['name' => preg_replace('/s+/', ' ', $request->input('name'))]);
return $next($request);
});
}

public function store(Request $request)
{
dd($request->all());
}

public function update(Request $request)
{
dd($request->all());
}
}



Edited, this is not documented in the Laravel 5.6


public function __construct()
{
$this->middleware(function ($request, $next) {

// replace any space+ to a single space
$request->merge(['name' => preg_replace('/s+/', ' ', $request->input('name'))]);
return $next($request);

})->only(['store', 'update']);
}





second argument to middleware, also builder methods to call after middleware
– lagbox
Jul 1 at 21:04


middleware


middleware





@lagbox i edited my question, is it correct/legit ? but it seems work LOL
– kenken9999
Jul 2 at 5:11




1 Answer
1



You can use like this



$this->middleware('auth',['only' => ['store','update']]);
// Another Way
$this->middleware('auth',['except' => ['index','show']]);


$this->middleware('auth',['only' => ['store','update']]);
// Another Way
$this->middleware('auth',['except' => ['index','show']]);



Reference: https://laracasts.com/discuss/channels/general-discussion/apply-middleware-for-certain-methods?page=0





but if without write a new middleware class, how can combine $this->middleware(function ($request, $next) and $this->middleware('i dont need a new class')->only('store');
– kenken9999
Jul 1 at 13:15


$this->middleware(function ($request, $next)


$this->middleware('i dont need a new class')->only('store');





You can use default 'auth' middleware
– Manvir Singh
Jul 1 at 13:19





i edited my question, because i'm not use auth middleware, i need modify the $request->input('name') before the variable pass to method
– kenken9999
Jul 1 at 13:48






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to add background colour in existing image using Swift?

What's the difference between DDS and SOME/IP?

Moria Casán