相同的路由但在Laravel 5.1路由中调用不同的控制器

时间:2015-11-30 10:48:50

标签: php laravel url-routing laravel-5.1 laravel-routing

我有两个网址用于分类,一个用于品牌,例如:

http://localhost/project/womens-fashion #category
http://localhost/project/babette-clothes #brand

我只想制作一条路线,但要打电话给不同的控制器。 我已经写了路线,但它不适合我的发送错误。见下面的代码:

<?php
use \DB;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Facades\Redirect;

Route::get('/','HomeController@index');
Route::get('/product', array('uses' => 'ProductController@index'));
Route::get('/{slug}', function($slug) {
    $result = DB::select('SELECT controller FROM url_setting where slug = ?', [$slug]);

    if ($result[0]->pw_us_controller == 'CategoryController@view') {
        return Redirect::action('CategoryController@view', array($slug));
    } elseif ($result[0]->pw_us_controller == 'CategoryController@view') {
        return Redirect::action('BrandController@index', array($slug));
    } else {
        return Redirect::action('HomeController@index');
    }
});

错误:InvalidArgumentException in UrlGenerator.php line 576: Action App\Http\Controllers\CategoryController@view not defined.

我很困惑,出了什么问题?任何想法!!!

2 个答案:

答案 0 :(得分:3)

您应该为CategoryController@view定义路线。

尝试在路线文件中添加以下内容:

Route::get('/category', 'CategoryController@view');

<强> --- --- EDIT

我只是更好地阅读了这个问题。我想你会得到这样的东西:

/womens-fashion --> CategoryController@view
/babette-clothes --> BrandController@view

你的数据库中存有slu ..

因此,或许重定向不是您的解决方案。

我会做这样的事情:

Route::get('/{slug}', 'SlugController@view');

controller SlugController

class SlugController extends Controller
{

  public function view(Request $request, $slug)
  {
    $result = DB::select('SELECT controller FROM url_setting where slug = ?', [$slug]);

    if ($result[0]->pw_us_controller == 'CategoryController@view') {
        return self::category($request, $slug);
    } else if ($result[0]->pw_us_controller == 'BrandController@view') {
        return self::brand($request, $slug);
    } else {
        // redirect to home
    }
  }

  private function category($request, $slug)
  {
    // Category controller function
    // ....
  }

  private function brand($request, $slug)
  {
    // Brand controller function
    // ....
  }

}

答案 1 :(得分:0)

您宁愿使用以下语法:

return redirect()->action('CategoryController@view', array($slug));