Laravel update only the changed field attribute(s)

Volka Dimitrev :

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');
    }
Matei Mihai :

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;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386751&siteId=1