向 Laravel 中的资源控制器添加新方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16661292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add new methods to a resource controller in Laravel
提问by user2403824
I want to know if it is possible to add new methods to a resource controller in Laravel and how you do it.
我想知道是否可以向 Laravel 中的资源控制器添加新方法以及如何添加。
I know that these methods are the default (index, create, store, edit, update, destroy). Now I want to add additional methods and routes to the same controller.
我知道这些方法是默认的(索引、创建、存储、编辑、更新、销毁)。现在我想向同一个控制器添加额外的方法和路由。
Is that possible?
那可能吗?
回答by Joseph Silber
Just add a route to that method separately, beforeyou register the resource:
在注册资源之前,只需单独添加到该方法的路由:
Route::get('foo/bar', 'FooController@bar');
Route::resource('foo', 'FooController');
回答by Antonio Carlos Ribeiro
I just did that, to add a GET "delete" method.
我就是这样做的,添加了一个 GET“删除”方法。
After creating your files, you just need to add
创建文件后,您只需要添加
'AntonioRibeiro\Routing\ExtendedRouterServiceProvider',
to 'providers' in your app/config.php
到您的 app/config.php 中的“提供者”
Edit the Route alias in this same file:
在同一个文件中编辑路由别名:
'Route' => 'Illuminate\Support\Facades\Route',
changing it to
将其更改为
'Route' => 'AntonioRibeiro\Facades\ExtendedRouteFacade',
And make sure those files are being autoloaded, they must be in some directory that you have in your composer.json ("autoload" section).
并确保这些文件正在自动加载,它们必须位于您的 composer.json(“自动加载”部分)中的某个目录中。
Then you just need to:
然后你只需要:
Route::resource('users', 'UsersController');
And this (look at the last line) is the result if you run php artisan routes
:
这(看最后一行)是你运行的结果php artisan routes
:
Those are my source files:
这些是我的源文件:
ExtendedRouteFacade.pas
ExtendedRouteFacade.pas
<?php namespace AntonioRibeiro\Facades;
use Illuminate\Support\Facades\Facade as IlluminateFacade;
class ExtendedRouteFacade extends IlluminateFacade {
/**
* Determine if the current route matches a given name.
*
* @param string $name
* @return bool
*/
public static function is($name)
{
return static::$app['router']->currentRouteNamed($name);
}
/**
* Determine if the current route uses a given controller action.
*
* @param string $action
* @return bool
*/
public static function uses($action)
{
return static::$app['router']->currentRouteUses($action);
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'router'; }
}
ExtendedRouter.pas
扩展路由器.pas
<?php namespace AntonioRibeiro\Routing;
class ExtendedRouter extends \Illuminate\Routing\Router {
protected $resourceDefaults = array('index', 'create', 'store', 'show', 'edit', 'update', 'destroy', 'delete');
/**
* Add the show method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @return void
*/
protected function addResourceDelete($name, $base, $controller)
{
$uri = $this->getResourceUri($name).'/{'.$base.'}/destroy';
return $this->get($uri, $this->getResourceAction($name, $controller, 'delete'));
}
}
ExtendedRouteServiceProvider.pas
扩展路由服务提供者.pas
<?php namespace AntonioRibeiro\Routing;
use Illuminate\Support\ServiceProvider;
class ExtendedRouterServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['router'] = $this->app->share(function() { return new ExtendedRouter($this->app); });
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('router');
}
}
回答by Mokhamad Rofi'udin
Yeah, It's possible..
是的,有可能。。
In my case I add method : data to handle request for /data.json in HTTP POST method.
在我的例子中,我添加了 method : data 来处理 HTTP POST 方法中对 /data.json 的请求。
This what I did.
这就是我所做的。
First we extends Illuminate\Routing\ResourceRegistrarto add new method data
首先我们扩展Illuminate\Routing\ResourceRegistrar来添加新的方法数据
<?php
namespace App\MyCustom\Routing;
use Illuminate\Routing\ResourceRegistrar as OriginalRegistrar;
class ResourceRegistrar extends OriginalRegistrar
{
// add data to the array
/**
* The default actions for a resourceful controller.
*
* @var array
*/
protected $resourceDefaults = ['index', 'create', 'store', 'show', 'edit', 'update', 'destroy', 'data'];
/**
* Add the data method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\Route
*/
protected function addResourceData($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).'/data.json';
$action = $this->getResourceAction($name, $controller, 'data', $options);
return $this->router->post($uri, $action);
}
}
After that, make your new ServiceProvideror use AppServiceProviderinstead.
之后,创建新的ServiceProvider或改用AppServiceProvider。
In method boot, add this code :
在方法boot 中,添加以下代码:
public function boot()
{
$registrar = new \App\MyCustom\Routing\ResourceRegistrar($this->app['router']);
$this->app->bind('Illuminate\Routing\ResourceRegistrar', function () use ($registrar) {
return $registrar;
});
}
then :
然后 :
add to your route :
添加到您的路线:
Route::resource('test', 'TestController');
Check by php artisan route:list
And you will find new method 'data'
检查php artisan route:list
你会发现新方法'数据'
回答by Hassan Jamal
Route::resource('foo', 'FooController');
Route::controller('foo', 'FooController');
Give this a try .Put you extra methods like getData() etc etc .. This worked for me to keep route.php clean
试试这个。给你额外的方法,比如 getData() 等。这对我保持 route.php 干净有用
回答by Patrick Lumenus
Just add a new method and a route to that method.
只需添加一个新方法和该方法的路由。
In your controller:
在您的控制器中:
public function foo($bar=“default”)
{
//do stuff
}
And in your web routes
在你的网络路线中
Route::get(“foo/{$bar}”, “MyController@foo”);
Just be sure the method in the controller is public.
只要确保控制器中的方法是公开的。
回答by Mazen Embaby
Using Laravel >5 Find the web.php file in routes folder add your methods
使用 Laravel >5 在 routes 文件夹中找到 web.php 文件添加你的方法
You can use route::resource to route all these methods index, show, store, update, destroy in your controller in one line
您可以使用 route::resource 将所有这些方法 index、show、store、update、destroy 路由到您的控制器中的一行中
Route::get('foo/bar', 'NameController@bar');
Route::resource('foo', 'NameController');
回答by mdamia
This works pretty good too. No need to add more routes just use show method of the resource controller like this :
这也很好用。无需添加更多路由,只需使用资源控制器的 show 方法,如下所示:
public function show($name){
switch ($name){
case 'foo':
$this -> foo();
break;
case 'bar':
$this ->bar();
break;
defautlt:
abort(404,'bad request');
break;
}
}
public function foo(){}
publcc function bar(){}
I use the default to throw custom error page.
我使用默认值抛出自定义错误页面。