【问题标题】:Is it possible to rewrite routes in Laravel 5, in routes file是否可以在路由文件中重写 Laravel 5 中的路由
【发布时间】:2015-04-20 12:39:02
【问题描述】:

是否可以在 Laravel 5 的 routes.php 文件而不是我的 .htaccess 文件中执行 URL 重写?我知道重定向很容易,但我最好避免这样做,以便将短网址保留在地址栏中。

假设我有将使用该路由的 url 'http://website.com/store/clothing/shites/cool-shirt':

Route::get('store/{category}/{subcategory}/{product}', [
    'uses'=>'StoreController@getProduct'
]);

我想创建一个快捷方式 URL 'http://website.com/cool-shirt',它会从数据库表中获取完整的 url,然后调用正确的路由和参数(无需重定向)。

Route::get('{slug}', function($slug){

    $shortcut = \App\Shortcut::whereSlug($slug)->first();

    // I'm making the execute_route() function up here
    return execute_route($shortcut->full_url);

})

基本上在路由中调用路由。

这可能吗?

【问题讨论】:

    标签: routes rewrite laravel-5


    【解决方案1】:

    我了解您想要实现的目标,而不是尝试在当前路由中调用另一条路由,我建议您仅对请求使用一条路由,在控制器中处理数据库查询并显示和返回基于当前的 slug 或抛出 404。

    像这样:

    Route::get('/{slug?}',array(
        'uses' => 'ShortcutController@getSlug',
        'as'   => 'shortcut.getSlug'
    ));
    
    
    
    <?php namespace App\Http\Controllers;
    
    use \View;
    use App\Shortcut;
    
    
    class ShortcutController extends Controller {
    
    
        public function getSlug($slug=null){
            if(!$shortcut = Shortcut::whereSlug($slug)->first()) abort(404);
            return view('slug')
                ->with('shortcut',         $shortcut);
    
        }
    
    }
    

    注意:上面的路由应该是你的 routes.php 中的最后一个列表,否则可能会匹配其他一些路由

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 2021-05-11
      • 2016-03-14
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 2021-02-26
      • 2015-05-14
      • 1970-01-01
      相关资源
      最近更新 更多