【问题标题】:Same route but call different controller in Laravel 5.1 routing相同的路由但在 Laravel 5.1 路由中调用不同的控制器
【发布时间】:2016-03-03 23:36:20
【问题描述】:

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

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.

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

【问题讨论】:

  • 显然您的CategoryController 中没有函数view()
  • 我的类 CategoryController 中有函数 view()。如果我使用这条路线: Route::get('/{slug}', 'CategoryController@view')->where('slug', '[A-Za-z-0-9]+');它正确路由
  • 路由并不意味着执行这样的逻辑,你可以做的是从路由中获取/发布单个函数上的数据,然后根据传递的数据将数据转移到不同的函数中。

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


【解决方案1】:

你宁愿使用这种语法:

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

【讨论】:

【解决方案2】:

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

尝试在你的路由文件中添加类似这样的内容:

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

---编辑---

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

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

并且您的数据库中存储了 slug。

所以,也许 redirect 不是您的解决方案。

我会这样做:

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

控制器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
    // ....
  }

}

【讨论】:

    猜你喜欢
    • 2013-09-24
    • 2016-03-29
    • 2017-04-05
    • 2016-10-03
    • 2021-05-26
    • 2018-10-20
    • 1970-01-01
    • 2018-12-12
    • 2018-09-10
    相关资源
    最近更新 更多