Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Giorgi's avatar

middleware in constructor and route variable

I have route:

Route::resource('companies', 'Companies');

and I need get $id in middleware, when I use edit() function. I have try like this:

public function __construct()
{
    $this->middleware(function ($request, $next) {
        if ( $request->route()->parameter('id') == 43 )  return redirect('/');
        return $next($request);
    })->only('edit');
}

but it doesn't work. Can anyone help me?

0 likes
2 replies
martinbean's avatar

@Giorgi Just check the ID in your actual edit() action?

public function edit($id)
{
    if ($id == 43) {
        return redirect('/');
    }

    $company = Company::findOrFail($id);

    return view('company.show', compact('company'));
}
Giorgi's avatar

Hi martinbean

I am going create middleware related edit(), show(), update() and destroy() functions. I wish create middleware and don't repeat same code.

Please or to participate in this conversation.