在laravel分形中使用first()

时间:2017-11-25 08:32:27

标签: laravel laravel-5.5

我想转换第一项联系人,这是我的代码

public function includeContact(Customer $customer)
{
    return $this->item($customer->contacts()->first(), new ContactTransformer);
}

但它无法正常工作,我收到此错误: 输入错误:参数1传递给

  

App \ Transformers \ ContactTransformer :: transform()必须是一个实例   App \ Models \ Contact,null给定,调用   * \供应商\联赛\分的\ src \ Scope.php   在第407行

被修改 这是ContactTransformer     

namespace App\Transformers;

use App\Models\Contact;
use League\Fractal\TransformerAbstract;

class ContactTransformer extends TransformerAbstract
{
    public function transform(Contact $contact)
    {
        return [
            'value' => $contact->value,
            'type' => $contact->communication->title,
            'icon' => $contact->communication->icon
        ];
    }
}

这是CustomerTransformer

class CustomerTransformer extends TransformerAbstract
{
    protected $availableIncludes = ['contacts', 'contact'];

    public function transform(Customer $customer)
    {
        return [
            'id' => $customer->id,
            'name'=>$customer->name,
            'status' => $customer->status,
            'tags' => $customer->tags->pluck('name'),
            'created_at' => Verta::instance($customer->created_at)->format('Y/n/j'),
        ];
    }

    public function includeContacts(Customer $customer)
    {
        return $this->collection($customer->contacts, new ContactTransformer);
    }

    public function includeContact(Customer $customer)
    {
        return $this->collection($customer->contacts, new ContactTransformer);
    }
}

1 个答案:

答案 0 :(得分:0)

这是因为您的一些客户没有联系人。在ContactTransformer方法上查看您的transform()课程,它应该会收到Contact的实例。如果您提供该方法null,那么它当然会失败。

然后,你需要这样,

class ContactTransformer extends TransformerAbstract
{
    public function transform(Contact $contact = null)
    {
        if (is_null($contact)) return null;

        return [
            'value' => $contact->value,
            'type' => $contact->communication->title,
            'icon' => $contact->communication->icon
        ];
    }
}