Append the auth:api middleware to any route or group of routes and the Bearer token will be checked automatically for you without a custom middleware
Route::get('url', 'controller@method')->middleware('auth:api');
But to answer the question, here's what you can do (still not recommended but works)
<?php
namespace App\Http\Middleware;
use Closure;
class ApiAuthentication
{
public function handle($request, Closure $next)
{
$token = $request->bearerToken();
$user = \App\User::where('api_token', $token)->first();
if ($user) {
auth()->login($user);
return $next($request);
}
return response([
'message' => 'Unauthenticated'
], 403);
}
}
Register the middleware in App\Http\Kernel
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
// Here for example
'custom_auth' => \App\Http\Middleware\ApiAuthentication::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
And protect a route with that middleware name
Route::get('/', function () {
// Return authenticated user model object serialized to json
return auth()->user();
})->middleware('custom_auth');
Result
