mohammednehru
3 months ago
487
7
Laravel

Nested relationships

Posted 3 months ago by mohammednehru

Hi,

I'm trying to access data from the request, I can for 'plan' but always return null in 'services'

This is my request and the same result here when dumping the validated data

array:3 [▼
  "_token" => "C76EvO3bpW4K7e2ogs20373OCkVxj9p1Lbv8fwcO"
  "plan" => array:3 [▼
    "price" => "2342"
    "ar_name" => "name in language one"
    "en_name" => "name in language two"
  ]
  "services" => array:2 [▼
    0 => array:3 [▼
      "ar_name" => "service one in language one"
      "en_name" => "service one in language two"
      "number" => "2"
    ]
    1 => array:3 [▼
      "ar_name" => "service two in language one"
      "en_name" => "service two in language two"
      "number" => "5"
    ]
  ]
]

ValidatedData function

    protected function validatedData()
    {
        return request()->validate([
            'plan.ar_name' => 'required',
            'plan.en_name' => 'required',
            'plan.price' => 'required',
            'services.*.ar_name' => 'required',
            'services.*.en_name' => 'required',
            'services.*.number' => 'required',
        ]);
    }

Data function

    protected function data()
    {
        return ([
            'plan' => [
                'ar' => [
                    'name' => request('plan.ar_name'),
                ],
                'en' => [
                    'name' => request('plan.en_name'),
                ],
                'price' => request('plan.price')
            ]
        ] +
            ['services' => [
                [
                    'ar' => [
                        'name' => request('services.*.ar_name'),
                    ],
                    'en' => [
                        'name' => request('services.en_name'),
                    ],
                    'number' => request('services.number')
                ],
            ]]);
    }

this is what data() returns

array:2 [▼
  "plan" => array:3 [▼
    "ar" => array:1 [▼
      "name" => "name in language one"
    ]
    "en" => array:1 [▼
      "name" => "name in language two"
    ]
    "price" => "2342"
  ]
  "services" => array:1 [▼
    0 => array:3 [▼
      "ar" => array:1 [▼
        "name" => null
      ]
      "en" => array:1 [▼
        "name" => null
      ]
      "number" => null
    ]
  ]
]

Please sign in or create an account to participate in this conversation.