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条)

报告相同问题?

悬赏问题

  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同
  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题