라 라벨의 리소스 컨트롤러에 새로운 메소드를 추가 할 수 있는지, 어떻게 하는지를 알고 싶습니다.
나는이 방법이 기본값이라는 것을 알고 있습니다 (색인, 생성, 저장, 편집, 업데이트, 파괴). 이제 동일한 컨트롤러에 메소드와 경로를 추가하고 싶습니다.
가능합니까?
라 라벨의 리소스 컨트롤러에 새로운 메소드를 추가 할 수 있는지, 어떻게 하는지를 알고 싶습니다.
나는이 방법이 기본값이라는 것을 알고 있습니다 (색인, 생성, 저장, 편집, 업데이트, 파괴). 이제 동일한 컨트롤러에 메소드와 경로를 추가하고 싶습니다.
가능합니까?
답변:
리소스를 등록 하기 전에 해당 메서드에 대한 경로를 별도로 추가하십시오 .
Route::get('foo/bar', 'FooController@bar');
Route::resource('foo', 'FooController');
Route::get('foo/{id}', ...). 이렇게 foo하면을 (를) 포함하여 하나의 추가 세그먼트로 시작하여 모든 경로를 삼킬 수 foo/bar있습니다.
방금 GET "delete"메소드를 추가하기 위해 그렇게했습니다.
파일을 만든 후 추가하면됩니다.
'AntonioRibeiro\Routing\ExtendedRouterServiceProvider',
app / config.php의 '제공자'에게
이 동일한 파일에서 라우트 별명을 편집하십시오.
'Route' => 'Illuminate\Support\Facades\Route',
로 변경
'Route' => 'AntonioRibeiro\Facades\ExtendedRouteFacade',
해당 파일이 자동으로로드되는지 확인하고 composer.json에있는 일부 디렉토리 ( "autoload"섹션)에 있어야합니다.
그런 다음 다음을 수행하면됩니다.
Route::resource('users', 'UsersController');
그리고이 (마지막 줄을 보면) 다음을 실행하면 결과가 나타납니다 php artisan routes.
그것들은 내 소스 파일입니다.
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
<?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
<?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');
}
}
예, 가능합니다 ..
내 경우에는 HTTP POST 메서드에서 /data.json에 대한 요청을 처리하기 위해 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);
}
}
그런 다음 새 ServiceProvider를 만들 거나 AppServiceProvider를 대신 사용하십시오.
메소드 부팅 에서 다음 코드를 추가하십시오.
public function boot()
{
$registrar = new \App\MyCustom\Routing\ResourceRegistrar($this->app['router']);
$this->app->bind('Illuminate\Routing\ResourceRegistrar', function () use ($registrar) {
return $registrar;
});
}
그때 :
경로에 추가하십시오 :
Route::resource('test', 'TestController');
확인 php artisan route:list
하면 새로운 방법 '데이터'를 찾을 수 있습니다
Route::resource('foo', 'FooController');
Route::controller('foo', 'FooController');
이것을 시도해보십시오 .getData () 등과 같은 추가 메소드를 넣으십시오. 이것은 route.php를 깨끗하게 유지하는 데 효과적이었습니다.
이것은 꽤 잘 작동합니다. 더 많은 경로를 추가 할 필요가 없습니다. 다음과 같이 리소스 컨트롤러의 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(){}
기본값을 사용하여 사용자 정의 오류 페이지를 발생시킵니다.
::resource그렇지 않으면 "모델에 대한 쿼리 결과가 없습니다"라는 오류 메시지가 표시됩니다.