Volka Dimitrev
Volka Dimitrev

Reputation: 387

Laravel update only the changed field attribute(s)

I'm trying to run this update function in my laravel controller. Here my domain name is an unique attribute.

The problem

But now every time when I'm trying to update any field rather than domain name field, it showing me an error saying domain name is already existing. So how can I update only the fields which have been changed? what changes do I need to be made in the following function.

public function update(Request $request,Website $app, $id)
    {
        $this->validate($request, [
            'subDomainName' => ['required'],
            'subDomainSuffix' =>['required'], 
            'packageType'=>['required'],
            'themeid'=>['required'],
            'lang'=>['required'],
            'user'=>['required'],
            'domain' => ['required', 'string','min:2', 'max:255','unique:apps'],
        ],$request->all());

        $fullDomain = $request->domain;
        $app->domain=$fullDomain;
        Website::find($id)->update($request->all());
        return redirect()->route('customers.index')
                        ->with('success','Website updated successfully');
    }

Upvotes: 0

Views: 547

Answers (1)

Mihai Matei
Mihai Matei

Reputation: 24276

You can specify a model to be ignored on the unique attribute:

public function update(Request $request, Website $websiteModel, int $id)
{
    $website = $websiteModel->find($id);

    $this->validate($request, [
        'subDomainName' => ['required'],
        'subDomainSuffix' => ['required'], 
        'packageType' => ['required'],
        'themeid' => ['required'],
        'lang' => ['required'],
        'user' => ['required'],
        'domain' => [
            'required',
            'string',
            'min:2',
            'max:255',
            Rule::unique('apps')->ignore($website)
         ],
    ], $request->all());

    $website->update($request->all());

    return redirect()
        ->route('customers.index')
        ->with('success','Website updated successfully');
}

Don't forget to import Rule: use Illuminate\Validation\Rule;

Upvotes: 1

Related Questions