如何将apiReources方法与`only`一起使用? [英] how to use apiReources method with `only`?

查看:61
本文介绍了如何将apiReources方法与`only`一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel创建一个api,并且正在寻找一种轻松的惰性方式来注册Api资源.我目前正在定义这样的路线:

I'm creating an api with Laravel and I am looking for a easy lazy way to to register Api resources. I'm currently defining my routes like this:

Route::apiResoruce('categories', 'CategoryController')->only(['index', 'show']);

我查看了 Laravel的控制器文档,我看到了 apiResources 方法,我可以一次创建多个api资源.

I checked Laravel's controller documentation and I saw apiResources method which I can create multiple api resources at once.

目标:能够将 apiResources 与像这样的 only 方法一起使用

the goal: is to be able to use apiResources with only method like this

Route::apiResources(['categories' => 'CategoryController', 'products' => 'ProductController'])->only(['index', 'show']);

当前结果:

Call to a member function only() on null

推荐答案

长话短说(如果您不想阅读整个故事),您可以这样做:

long story short (if you don't want to read the whole story) you can just do it like this:

Route::apiResources(['brands' => 'BrandController', 'categories' => 'CategoryController'], ['only' => ['index', 'show']]);

当我写问题时,它浮现在我的脑海中去检查 apiResources 声明,我发现了这一点:

When I was writing the question it passed to my mind to check the apiResources declaration and I found this:

   /**
     * Register an array of API resource controllers.
     *
     * @param  array  $resources
     * @param  array  $options
     * @return void
     */
    public function apiResources(array $resources, array $options = [])
    {
        foreach ($resources as $name => $controller) {
            $this->apiResource($name, $controller, $options);
        }
    }

并且由于它在后台使用了 apiResource 并且它传递了options参数,因此我可以检查这些选项是什么

and since it is using apiResource under the hood and it is passing options parameter I can check what are these options

/**
 * Route an API resource to a controller.
 *
 * @param  string  $name
 * @param  string  $controller
 * @param  array  $options
 * @return \Illuminate\Routing\PendingResourceRegistration
 */
public function apiResource($name, $controller, array $options = [])
{
    $only = ['index', 'show', 'store', 'update', 'destroy'];

    if (isset($options['except'])) {
        $only = array_diff($only, (array) $options['except']);
    }

    return $this->resource($name, $controller, array_merge([
        'only' => $only,
    ], $options));
}

这篇关于如何将apiReources方法与`only`一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆