利用宏设置快捷路由跳转

在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 于 6年前 加精
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!