mercredi 11 juillet 2018

In laravel hasmany relationship data is not displayed/fetched straight after creating them

I have a store method where it saves or update adult details for an advice file.

Relationships:

An AdviceFile hasMany Adult
An Adult belongsTo an AdviceFile

I think my method is straightforward (might be wrong), but at the end when I try to fetch adults belonging to the adviceFile it doesn’t fetch any.

Any idea why this may happen?

Here is my store method

public function store(AdviceFile $adviceFile, AdultDataRequest $request)
    {
        $requestData = $request->data;

        foreach ($requestData as $adultDetails) {
            if (isset($adultDetails["id"])) {
                // Update the record
                $keysToExclude = [
                    'id', 'advice_file_id', 'created_at', 'updated_at', 'deleted_at'
                ];
                $data = array_except($adultDetails, $keysToExclude);
                $adult = Adult::find($adultDetails["id"]);
                $adult->data = $data;
                $adult->save();
            } else {
                // Create record
                Adult::create([
                    'advice_file_id' => $adviceFile->id,
                    'data' => $adultDetails
                ]);
            }
        }
        //This is where I get an empty response, even though there is data in db
        return AdultResource::collection($adviceFile->adults); 
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire