【问题标题】:Model binding in nested resources in LaravelLaravel 嵌套资源中的模型绑定
【发布时间】:2016-12-30 07:01:28
【问题描述】:

我正在 Laravel 中构建一个 RESTful api,我的前端应用程序在 Angular 中。

我有许多模型/控制器和路线。我正在努力为嵌套资源创建宁静的路线。

例如,我显示客户列表的路线很简单:

 Route::resource('clients', 'ClientsController');

一个客户可以有多个广告系列:

class Client extends Model
{

    public function campaigns()
    {
        return $this->hasMany('App\Campaign');
    }

}

我不需要显示所有广告系列的路线,但我确实需要显示基于客户的所有广告系列的路线。

Route::resource('clients.campaigns', 'CampaignsController');

我的意图是让 Angular 应用程序请求的端点是:

myapp/api/clients/6/campaigns

其中“6”是客户端 ID。这将返回属于 id 为 6 的客户的广告系列列表。

在我的索引方法中,我尝试使用隐式模型绑定来获取此客户端 ID,但我总是得到一个空结果集:

class CampaignsController extends ApiController
{

    public function index(Client $client)
    {
        $campaigns = Campaign::where('client_id', $client->id)->get();
        if (!count($campaigns)) {
            Log::warning('Campaigns list is empty');
            return $this->respondNotFound('No Campaigns Found');
        }

        try {
            return $this->respond([
                'data' => $this->campaignTransformer->transformCollection($campaigns->all())
            ]);
        } catch (\Exception $e) {
            Logging::logException($e, 'API error showing campaigns list');
            return $this->respondInternalError('An internal error occurred');
        }
    }

}

显然我的路由没有绑定客户端——$client 上的 var_dump 显示了这一点。 我哪里错了?

【问题讨论】:

    标签: php angularjs laravel


    【解决方案1】:

    对于遇到此问题的任何人 - Laravel 正在为我注入 client_id。

    因此索引方法变为:

    public function index($client_id)
    {
        $campaigns = Campaign::where('client_id', $client_id)->get();
    }
    

    【讨论】:

    • 我面临同样的问题...为什么我必须使用$client_id 而不是Client $client,我想要模型绑定:D
    • @Zalo 你想要隐式模型绑定 - laravel.com/docs/5.7/routing#route-model-binding
    • @DJC 是的,但是资源控制器中没有关于模型绑定的信息。
    猜你喜欢
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多