tspesh

Best way to dynamically edit a model

Posted 8 months ago by tspesh

Let's say you have a pretty large model and in various places you might update different parts of that model...

I feel like your options are to create a controller for each "part" of the model you are editing (in my example below we may be updating contact information). Or you can loop through each request and set the model's attributes dynamically, IE something like this:

foreach($request->all() as $key => $request){
    $model->{$key} = $request;
}

$model->save();

I am using the $fillable array so I think that would be safe...but it feels funky. So for the time being I'm doing something this:

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Order  $quote
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Order $quote)
    {
        if($request->has('update_billing')){
            $quote->billing_address_1   = $request->billing_address_1;
            $quote->billing_address_2   = $request->billing_address_2;
            $quote->billing_city        = $request->billing_city;
            $quote->billing_country     = $request->billing_country;
            $quote->billing_state       = $request->billing_state;
            $quote->billing_phone       = $request->billing_phone;
        }

        if($request->has('update_contact')){
            $quote->contact_address_1   = $request->contact_address_1;
            $quote->contact_address_2   = $request->contact_address_2;
            $quote->contact_city        = $request->contact_city;
            $quote->contact_country     = $request->contact_country;
            $quote->contact_state       = $request->contact_state;
            $quote->contact_phone       = $request->contact_phone;
        }

        $quote->save();
    }

How would you go about it?

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