Return Instance with relationships after saving it.

Posted 1 year ago by GuntarsV

How do I return the saved instance with Relationship. Below is the store method, I would like to return the $savedRequest with cropInputMaterial information from another table. Code below doesn't work.

public function store(Request $request)
    {
        $this->validate($request,[
            'dairy_crop_id'=>'required|numeric',
            'crop_input_material_id'=>'required|numeric',
            'rate'=>'required|numeric',
            'cost_per_ac'=>'required|numeric',
            'applied_at'=>'required|date',
        ]);
        $attributes=$request->all();
        $attributes['applied_at']= convertToCarbonObj($request->applied_at);
        $savedRequest=DairyCropInput::create($attributes);
        return $savedRequest->with('cropInputMaterial');
    }

Here is the relation ship I created to cropInputMaterial

public function cropInputMaterial()
    {
        return $this->hasMany(Crop::class);
    }

I know that I could do another query after saving like this:

return FarmCrops::with('cropInputMaterial')->get();

But wouldn't that be a little inefficient, since I have the $savedRequest already? Suggestions are greatly appreciated!! I would like to have a clean and efficient code. Thanks.

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

Reply to

Use Markdown with GitHub-flavored code blocks.