Laravel 5条件路由和多个控制器 [英] Laravel 5 conditional routing and multiple controllers

查看:85
本文介绍了Laravel 5条件路由和多个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我的应用程序有两种类型的动态网址.

So basically my app has two types of dynamic url..

  1. app.com/{page}
  2. app.com/{user}

都有自己的控制器

  1. PageController @ index
  2. User \ ProfileController @ index

但是我正在努力使它工作.

But I'm struggling to get this working.

我尝试了几种不同的方法.这是我尝试过的两个..

I have tried a few different methods. Here are two I have tried..

Route::get('{slug}', function($slug) {
    if (App\Page::where('slug', $slug)->count()) {
        // return redirect()->action('PageController@index', [$slug]);
        // return App::make('App\Http\Controllers\PageController', [$slug])->index();
        return 'Page found';
    } else if (App\User::where('username', $slug)->count()) {
        // return redirect()->action('User\ProfileController@index', [$slug]);
        // return App::make('App\Http\Controllers\User\ProfileController', [$slug])->index();
        return 'User found';
    } else {
        return abort(404);
    }
});

我觉得我应该使用中间件/过滤器来做到这一点.任何帮助将是巨大的.谢谢.

I feel I should be doing this with middleware/filters. Any help would be great. Thanks.

推荐答案

我认为您可以通过Route::group使用中间件来过滤页面或用户,从而实现Route::group的目标.

I think you could achieve what you after with Route::group using a middleware to filter if it is a page or a user.

Route::group(['middleware' => 'isPage'], function () {
    Route::get('{slug}', ['as'=> 'pages.show', 'uses' => 'PageController@show']);
});

Route::group(['middleware' => 'isUser'], function () {
    Route::get('{slug}', ['as'=> 'users.show', 'uses' => 'User\ProfileController@show']);
});

这篇关于Laravel 5条件路由和多个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆