I am building an API with Laravel 5.3. I have routes such as /users/1, users/1/teams etc.
I'd like client applications to also be able to use URIs like /users/self, /users/self/teams.
I was looking into building a middleware that checks to see if /self/ is in the request URI and if it is, then change /self/ to the user's actual id, or do an internal redirect to the requested endpoint.
Any ideas on how I could do this?
Create middleware and use it:
1) create middleware:
file: app/Http/Middleware/ReplaceSelfToId.php
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ReplaceSelfToId
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if($request->route('id') == 'self') { // if id is self
if(!$request->user()) { // but user not instantiated
return redirect()->route('auth'); // redirect to auth
}
$request->route()->setParameter('id', $request->user()->id); // replace id to user's id
}
return $next($request);
}
}
2) register middleware in Kernel.php:
<?php
namespace App\Http;
use App\Http\Middleware\ReplaceSelfToId; // use middleware
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
ReplaceSelfToId::class // add this line to end of array (cuz have to get session initialized)
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With