利用宏设置快捷路由跳转
在Laravel 5.5 版本中已经存在重定向路由的功能,如下:
Route::redirect('/here', '/there', 301);
但是还是觉得用起来不是很顺手,例如我们想要重定向到定义好的路由上去,这时候就有点尴尬了,必须知道路由的地址才可以进行跳转。看了下Router的类,发现这个类有使用了Illuminate\Support\Traits\Macroable这个Trait,那就方便很多了。
在App\Libs\Route下建个类,如下
<?php
namespace App\Libs\Route;
use Illuminate\Support\Facades\Route;
class RouteMacroHandler
{
public static function macro() {
Route::macro('route_redirect', [static::class, 'route_redirect']);
}
public static function route_redirect($uri, $destination, $parameters = [], $status = 301) {
if ( is_integer($parameters) ) {
$status = $parameters;
$parameters = [];
}
return Route::any($uri, '\App\Libs\Route\RedirectController')
->defaults('destination', $destination)
->defaults('parameters', $parameters)
->defaults('status', $status);
}
}
然后在App\Libs\Route新建个跳转的控制器,如下:
<?php
namespace App\Libs\Route;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Controller;
use Illuminate\Routing\Router;
class RedirectController extends Controller
{
protected $router;
public function __construct(Router $router) {
$this->router = $router;
}
public function __invoke($destination, $parameters = [] , $status = 301)
{
if ( $this->router->has($destination) ) {
$destination = route($destination, $parameters);
}
return new RedirectResponse($destination, $status);
}
}
最后一步,在App\Providers\AppServiceProvider注册的时候添加下我们定义好的宏,如下:
public function register()
{
// 注册路由宏
\App\Libs\Route\RouteMacroHandler::macro();
}
现在到见证奇迹发生的时候了,具体使用方法如下,在routes/web.php下面添加几个路由进行测试:
Route::route_redirect('/here', 'there_name', ['type'=> 1, 'xx'=> 2], 301)->name('here_name');
Route::route_redirect('/here_302', 'there_name', 302)->name('here_302_name');
Route::get('/there', function(){ return 'there' })->name('there_name');
打开浏览器访问下吧
本帖已被设为精华帖!
本帖由 Summer
于 7年前 加精