I am trying to implement this example code by jeff ochoa which lets you redirect a request to a specific-route in laravel.
https://jeffochoa.me/redirect-a-request-to-a-specific-route-laravel
I'm getting this error when I run the code:
Got error 'PHP message: [31 /.../app/Providers/RouteServiceProvider.php 0 Argument 1 passed to Illuminate\\Routing\\Router::App\\Providers\\{closure}() must be an instance of Request, instance of Illuminate\\Http\\Request given]'
Can anyone tell me where I'm going wrong? The $request object is already pre-defined as an Illuminate\Http\Request when it's received so is it possible to convert it or ??
Here's my current code...
I have added this route into /routes/api.php
Route::group(['namespace' => 'API'],function() {
Route::get('/test',"testAPIController@get");
Route::get('macro.test', ['as' => 'macro.test', 'uses' => 'testAPIController0@get']);
});
I have added the Route::macro to /app/providers/RouteServiceProvider.php:
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
Route::macro(
'sendToRoute',
function (Request $request, string $routeName) {
$route = tap($this->routes->getByName($routeName))->bind($request);
$this->current = $route;
return $this->runRoute($request, $this->current);
}
);
parent::boot();
}
The controller that's calling the macro:
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Route;
class testAPIController extends AppBaseController
{
public function get(Request $request)
{
return Route::sendToRoute($request,"macro.test");
}
}
?>
The target Controller:
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
class testAPIController0 extends AppBaseController
{
public function get(Request $request) {
die("Hello World");
}
}
?>
In the definition of macro function, you should register the Illuminate\Http\Request
instead of only Request
. Like this:
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
Route::macro(
'sendToRoute',
function (\Illuminate\Http\Request $request, string $routeName) {
$route = tap($this->routes->getByName($routeName))->bind($request);
$this->current = $route;
return $this->runRoute($request, $this->current);
}
);
parent::boot();
}
Of course you can also import the Illuminate\Http\Request
on top of php file