Laravel 5.6将中间件应用于控制器的某些方法

时间:2018-07-01 12:59:23

标签: laravel

Laravel 5.6将中间件应用于控制器的某些方法

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

无需编写新课程

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());
    }
}

已编辑,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']);
    }

1 个答案:

答案 0 :(得分:0)

您可以这样使用

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

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