Jman
271
4
Laravel

Middleware causes Route Note Defined error..?

Posted 1 year ago by Jman

Hi all,

I'm working with Middleware for the first time and hit an issue I can't figure out.

I have users, and users can have a business. Naturally, I don't want users editing each others businesses by manually entering the business id in the url. Middleware seems like the right approach here. However, when I add the middleware to the route, I get an error saying that a route that is used in the view (the destination for the form in the edit view) is not defined. Which is incorrect, because it is correctly named and works just fine when I remove the '->middleware()' call.

The confusing thing is, I'm using a debugger and I can't seem to get it to hit the breakpoint I've set in the middleware. And if I 'dd($business)' in the view, when using the Middleware, it seems the '$business' variable is null, but without the Middleware the model is correctly assigned.

Completely lost, and I can't seem to narrow this one down any further...

Any ideas?

Route

/**
 * Frontend Controllers
 * All route names are prefixed with 'frontend.'.
 */
Route::get('business/{business}/edit', '[email protected]')->name('business.edit')->middleware('verify_business_owner:'.$business->id);
Route::patch('business/{business}', '[email protected]')->name('business.update');

Kernel.php

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password_expires' => \App\Http\Middleware\PasswordExpires::class,
        'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
        'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verify_business_owner' => \App\Http\Middleware\VerifyBusinessOwner::class
    ];

Middleware

namespace App\Http\Middleware;

use Closure;
use App\Models\Business;

class VerifyBusinessOwner
{
    /**
     * Handle an incoming request.
     * @todo improve check with function in model


     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, Business $business)
    {
        $response = $next($request);

        $user = $request->user();
        if($business->user_id != $user->id){
            return redirect('home');
        }

        return $response;
    }
}

Please sign in or create an account to participate in this conversation.