Jordan
Jordan

Reputation: 912

How can I "override" middleware in Laravel/Lumen 5?

I currently have an Angular application with Lumen serving as a back-end. My method of using a catch-all route is a global middleware that returns the Angular master file. How can I best go about adding API routes that don't pass through this middleware? Do I have to not use global middleware and instead have a route group? Is there a way I can test it inside of the middleware? Here is the current middleware I have:

<?php

namespace App\Http\Middleware;

use Closure;

class ToAngular
{
    public function handle($request, Closure $next)
    {
        return view('master');
    }
}

Upvotes: 0

Views: 818

Answers (1)

jszobody
jszobody

Reputation: 28959

404 Handler

I would personally avoid middleware in this scenario. If you want a catch-all, you're essentially defining a custom 404 handler. So I would approach it that way.

I'd open app/Exceptions/Handler.php and add a condition in the render method.

Something like:

public function render($request, Exception $e)
{
    if($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
    {
        return view('master');
    }

    return parent::render($request, $e);
}

Now you can define API routes and they'll just work, anything else will fall to this 404.

Alternatively you could just create a page at resources/views/errors/404.blade.php and have it extend your master view, that would accomplish the same thing, though a 404 HTTP header would be included I think.

Examine route segments

If you really want to stick with middleware, you could have it examine the request route segments. That way you can skip the catch-all view if this is a legit API request.

Assuming your valid API endpoints all start with /api/, you could do:

public function handle($request, Closure $next)
{
    if($request->segment(1) == "api") {
        // This is a valid api request! Let it proceed
        return $next($request);
    }

    // Otherwise return the master view
    return view('master');
}

Upvotes: 1

Related Questions