doucan2102 2017-11-03 09:54
浏览 87
已采纳

Laravel - 具有参数的单个控制器的多个资源路由

Can we have a single controller for multiple routes, and get the parameter?

Currently, I have these routes:

Route::resource('/customers', 'CustomerController');
Route::resource('/agents', 'AgentController');

And a CustomerController and a AgentController with all resource functions working.

But as CustomerController and AgentController are almost same except for one database field, i.e. group_id. I was thinking to use one controller i.e. PartyController and one route as:

Route::resource('/parties/customers', 'PartyController ');
Route::resource('/parties/agents', 'PartyController ');

or if someone suggests:

Route::resource('/parties/{group}', 'PartyController ');

I have been searching for a while but finding it hard to follow this path. I've added this code in the constructor of PartyController, to check the calling route:

    $path = Request::capture()->path();
    $this->group = ucwords(explode("/", $path)[1]);
    echo($this->group );

All seems to be going well till here. But when in my index.blade.php, I have this statement:

<p>{{ link_to_route('parties.create', 'Add new') }}</p>

I get an exception:

Route [parties.create] not defined. 

I've tried multiple combinations, without any success and more errors come through, like accessing /parties/customers/create doesn't work now.

So, is it possible anyway or should I abandon this idea?

EDIT: My question is different from Same Laravel resource controller for multiple routes as I am not using a trait.

  • 写回答

5条回答 默认 最新

  • dqjcb132285 2017-11-13 08:35
    关注

    I did it by using my own approach, I used the same routes.

    Route::resource('/parties/agents', 'PartyController');
    Route::resource('/parties/customers', 'PartyController');
    

    and in constructor of PartyController

    $path = Request::capture()->path();
    $group = strtolower(explode("/", $path)[1]);
    

    Now I've the $group variable to identify which group I am working with.

    And in my blade documents I replaced parties.create with $group.create

    <a href="{{ route($group.'.create')}}" > Add new </a>
    

    Same for other routes.. Now it is working just as I wanted.

    Thank all for help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度